Bryan Bryan - 1 year ago 74
JSON Question

Setting value of key in array based on value of another array

I've attached a codepen ( of a working concept of what I'm trying to accomplish. This working code assigns a name to an null value of the name key in the JSON object based on the respective position in the defaultNameArray.

My problem is with code in which I attempt to generate the defaultObj array in code for a length equal to the defaultNameArray.

var defaultNameArray = ["Bob", "Alice", "Joe"];

var defaultObj = [
"name": null,
"age": "32",
"height": "175",
"etc": "someData",

for (var i = 0; i < defaultNameArray.length -1; i++) {

for (var i = 0; i < defaultObj.length; i++) {
defaultObj[i].name = defaultNameArray[i];
console.log("defaultObj[i].name: " + defaultObj[i].name);
console.log("defaultNameArray[i]" + defaultNameArray[i]);

var str = JSON.stringify(defaultObj);
console.log('defaultObj: ' + str);

This code generates a generic array that I should then be able to iterate through to assign values to a key, with respect to the position in another array (names). The end result is all of the names being "Joe", the last position in the names array. Why does iterating through a generated array of JSON behave differently than using one defined in the code like the attached codepen, and what am I missing?

Answer Source

This pushes the same object with it's reference to the array so when you change one property in one of them you change in all. That's why in the end they only have the value of the last element.

Try defaultObj.push(Object.assign({}, defaultObj[0]));

Object assign documentation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download