-2

I'm trying to pass objects into an array within a for loop. The value keeps getting overwritten.

const files = require("./getFiles")();

module.exports = function templating() {
  let design = JSON.parse(files[1]),
    data = JSON.parse(files[2]),
    count = Object.keys(data).length,
    x = [];
  for (let i = 0; i < count; i++) {
    let tempDesign = design,
      tempData = data;
    tempDesign.columns[0].items[0]["url"] = tempData[i].url;
    tempDesign.columns[1].items[0]["text"] = tempData[i].name;
    tempDesign.columns[1].items[1]["text"] = tempData[i].desc;
    tempDesign.columns[1].items[2]["facts"][0]["value"] = tempData[i].priceText;
    tempDesign.columns[1].items[3]["actions"][0]["data"] = tempData[i].price;
    x.push(tempDesign);
  }
  return x;
};

I want my output to look something like this :

sample= [
    {
     "x":"data",
     "y":"data"
    },
    {
     "a":"data",
     "b":"data"
    },
    {
     "c":"data",
     "d":"data"
    },
    {
     "e":"data",
     "f":"data"
    },
   ]

Instead I get this :

sample= [
    {
     "e":"data",
     "f":"data"
    },
    {
     "e":"data",
     "f":"data"
    },
    {
     "e":"data",
     "f":"data"
    },
    {
     "e":"data",
     "f":"data"
    }
   ]

The loop pushes only the last object to the array but with the right count.

1 Answers1

1

This line here:

let tempDesign = design,

will create a reference to the variable design. (In case you don't know what a reference is, think of it as an alternative name to an existing variable). Later, after you modify the contents of tempDesign, you push it to the array. The new array element holds a reference to design.

Now, if we look at the next (possible) iteration of your for-loop, the new variable tempDesign is another reference to the same variable design, which is already referred to by the 1st element in the array x, and that is pushed to the array! And so, every next iteration of your for-loop pushes another, duplicate reference to the array x, all of which refer to the same variable design.

The fix is to make a copy of the variable design to avoid creating the showcased reference "maze". There are multiple methods of cloning objects in JavaScript, but this simple yet effective method should do the trick in your use case:

let tempDesign = JSON.parse(JSON.stringify(design));

This will make a new variable tempDesign, which is an object on its own, and thus isn't a reference to design anymore, while holding all data originally contained in design.

ijnkawakaze
  • 118
  • 1
  • 1
  • 8