[英]How to append arrays to existing json array and write to file in node js
I have a example.json
file. 我有一个example.json
文件。
{
"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. 在这里,我需要向第tc[0]th
索引添加另一个数组。 In Node JS
I tried this: 在Node JS
我尝试了以下操作:
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
. 但是在打印该obj
, obj.tc[0]
已替换为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. 我也想将此写回相同的json
文件。 I'm trying to achieve here a file containing number of tc
s with unique names. 我试图在这里实现一个包含多个具有唯一名称的tc
的文件。 Furthermore one tc
can have multiple bc
s, and bc
has a name attribute. 此外,一个tc
可以具有多个bc
,并且bc
具有名称属性。
I also accept suggestion on a better json
structure to support this concept. 我也接受关于更好的json
结构以支持此概念的建议。
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. 它使用对象o
放置新值,并使用值对象v
包含要分配的键和项目。
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>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.