I have a example.json
file.
{
"tc" :
[
{"name" : "tc_001"},
{"name" : "tc_002"},
{"name" : "tc_003"},
{"name" : "tc_004"},
{"name" : "tc_005"}
]
}
In here I need to add another array to the tc[0]th
index. In Node JS
I tried this:
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('example.json', 'utf8'));
var arr1 = {bc :[{name:'bc_001'}]}
var arr2 = {bc :[{name:'bc_002'}]}
obj.tc[0] = arr1;
obj.tc[0] = arr2;
But when printing that obj
, obj.tc[0]
has replaced by value of arr2
. The final result I want to achieve is:
{
"tc" :
[
{
"name" : "tc_001"
"bc" :
[
{"name" = "bc_001"},
{"name" = "bc_002"}
]
},
{"name" : "tc_002"},
{"name" : "tc_003"},
{"name" : "tc_004"},
{"name" : "tc_005"}
]
}
I also want to write this back to the same json
file. I'm trying to achieve here a file containing number of tc
s with unique names. Furthermore one tc
can have multiple bc
s, and bc
has a name attribute.
I also accept suggestion on a better json
structure to support this concept.
A solution for more than one item to add to the object.
It uses an object o
where the new values should go and a value object v
with the keys and the items to assign.
Inside it iterates over the keys and build a new array if not already there. Then all values are pushed to the array.
function add(o, v) { Object.keys(v).forEach(k => { o[k] = o[k] || []; v[k].forEach(a => o[k].push(a)); }); } var obj = { "tc": [{ "name": "tc_001" }, { "name": "tc_002" }, { "name": "tc_003" }, { "name": "tc_004" }, { "name": "tc_005" }] }; add(obj.tc[0], { bc: [{ name: 'bc_001' }] }); add(obj.tc[0], { bc: [{ name: 'bc_002' }] }); document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
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.