如何将数组附加到现有的json数组并在node js中写入文件

时间:2022-03-31 19:29:27

I have a example.json file.

我有一个例子。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. In Node JS I tried this:

在这里,我需要向tc[0]索引添加另一个数组。在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. The final result I want to achieve is:

但是打印obj的时候。用arr2的值替换tc[0]。我想要达到的最终结果是:

{
  "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 tcs with unique names. Furthermore one tc can have multiple bcs, and bc has a name attribute.

我还想把它写回相同的json文件。我试图在这里实现一个包含有多个具有唯一名称的tcs的文件。此外,一个tc可以有多个bc,而bc有一个name属性。

I also accept suggestion on a better json structure to support this concept.

我也接受关于更好的json结构来支持这个概念的建议。

1 个解决方案

#1


3  

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>');

#1


3  

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>');