skip to Main Content

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


  1. You’re always pushing the same object into the array and then modifying it. You need to create a new object every time:

    for(let i = 0 ; i < data.records.length ; i++) {
        // moved inside to create a new object instead of modifying the existing one
        var object = { i: 0, id: 0, number: "" };
        object.i = i;
        object.id = data.records[i].id;
        object.number = data.records[i].number;
        console.log("object: " + JSON.stringify(object));
        editableArray.push(object);
    }
    console.log("array:", editableArray);
    
    Login or Signup to reply.
  2. @Jensv answer is totally correct, just want to add my solution.

    It basically does the same things, it’s just a little less verbose.

    const data = {"records":[{"id":2463534,"token":"135","name":"MNC Rental","number":"0"},{"id":2463535,"token":"132","name":"ZNC Rental","number":"0"}]}
    
    const editableArray = data.records.map(({ id, number }, i) => ({ i, id, number: String(number) }));
    
    console.log("array: " + JSON.stringify(editableArray));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search