I’m trying to create an array of objects with nested arrays, but data is going missing in the last step:
const args_arr = [];
const options_arr = [];
let options = '';
let text = "";
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (i === j) {
args_arr.push(true);
} else {
args_arr.push(false);
}
}
text += args_arr + "<br>";
options = {
op1: true,
op2: false,
args: ['visible']
};
text += JSON.stringify(options) + "<br>";
options.args.push(args_arr);
text += JSON.stringify(options) + "<br>";
options_arr.push(options);
args_arr.length = 0;
}
text += '<br>' + JSON.stringify(options_arr) + "<br>";
document.getElementById("demo").innerHTML = text;
<pre id="demo"></pre>
Everything works as expected, but at the last step where I push options into options_arr the arrays after ‘visible’ goes missing.
Here’s the result:
true,false,false,false,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[true,false,false,false,false]]}
false,true,false,false,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,true,false,false,false]]}
false,false,true,false,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,false,true,false,false]]}
false,false,false,true,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,false,false,true,false]]}
false,false,false,false,true
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,false,false,false,true]]}
[{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]}]
What am I doing wrong?
>Solution :
The problem is because you push the args_arr into the options_arr and modify the info afterwards.
Change options.args.push(args_arr); to options.args.push([...args_arr]);
What it will do is copy the values from args_arr into a new array. This way it will not reset on every loop.