Need help figuring this out.. I want to create nested Javascript Object dynamically..
I have got a key, which has multiple values that needs to be nested per value in an array. For example:
{
"name": [{
"desc": "A",
"age": 26,
"name": [{
"desc": "B",
"age": 12,
"name": [{
"desc": "C",
"age": 48
}]
}]
}]
}
So far i have this:
var data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]]
const name = "name"
var json = {};
var current = json;
for (var i = 0; i < data.length; i++) {
current[name] = data[i];
current = current[name];
}
console.log(JSON.stringify(json));
Which only returns the first item in the data array.
{
"name": [{
"desc": "A",
"age": 26
}]
}
jsoncontains a regular object (hence the name of the variable is wrong). And there's no such thing as a "JSON Object".