2

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

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

1
  • what do you mean by better object structure? it depends on the purpose. Commented Apr 21, 2016 at 8:53

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry i edited the question. i want to add two bcs to tc one. Could you please edit the answer
It's working but hard to understand function add(o, v). Could you please simplify that if it's possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.