my data element contains:
{"records":[{"id":2463534,"token":"135","name":"MNC Rental","number":"0"},{"id":2463535,"token":"132","name":"ZNC Rental","number":"0"}]}
This is my code:
var editableArray = [];
var object = { i: 0, id: 0, number: "" };
for(let i = 0 ; i < data.records.length ; i++) {
object.i = i;
object.id = data.records[i].id;
object.number = data.records[i].number;
console.log("object: " + JSON.stringify(object));
editableArray.push(JSON.stringify(object));
}
console.log("array: " + JSON.stringify(editableArray));
Output:
object: {"i":0,"id":2463534,"number":"0"}
object: {"i":1,"id":2463535,"number":"0"}
array: ["{"i":0,"id":2463534,"number":"0"}","{"i":1,"id":2463535,"number":"0"}"]
So in the array there are a lot of backslashes and I dont know why. Anyone have an idea to avoid these backslashes?
If I remove the JSON.stringify in the push command, then it adds only the last object 2 times, this is the result:
array: [{"i":1,"id":2463535,"number":"0"},{"i":1,"id":2463535,"number":"0"}]
2
Answers
You’re always pushing the same object into the array and then modifying it. You need to create a new object every time:
@Jensv answer is totally correct, just want to add my solution.
It basically does the same things, it’s just a little less verbose.