简体   繁体   中英

javascript adding items to json object using a nested array

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]...

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])};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM