Home > Enterprise >  javascript adding items to json object using a nested array
javascript adding items to json object using a nested array

Time:04-06

so i have one array with names, and one with other json-data i can access using a method. I was trying to do

let out = [];

for (let i = 0; i < data.length; i  ) {
    for (let j = 0; j < names.length; j  ) {
        let feed = {names[j] : getData(data[i])};
        out.push(feed);
    }
}

So the expected output would be an array a bit like this: [{"jonas": {"a" : 1, "b": 2}}, {"lara" : {"a": 73, "b": 0}}, "jakob": {"a" : null, "b": "something"}]

What actually happened was an error occuring: unecpected token '[' ment was the '[' at ...let feed = {names[ /←this here/ j]...

CodePudding user response:

It looks like you need computed property names.

let feed = { [names[j]]: getData(data[i]) };
//           ^        ^

CodePudding user response:

In order to use a variable as a key to an object you need to enclose it in [], try using this let feed = {[names[j]] : getData(data[i])};

  • Related