1

I have a JSON input which can go to any number of levels.

Here is the sample

var testJSON = [
    {
      'name':'USER1',
      'id':1,
      'child':[],
    },{
      'name':'USER2',
      'id':2,
      'child':[{
           'name':'USER2_CHILD1',
           'id':21,
           'child':[]
         },{
           'name':'USER2_CHILD2',
           'id':22,
           'child':[{
              'name':'USER2_CHILD2_CHILD1',
              'id':221,
              'child':[]
            }]
        }],
    },{
      'name':'USER3',
      'id':3,
      'child':[{
        'name':'USER3_CHILD1',
        'id':31,   
        'child':[]
      }],
    }];

I want to add a JSON data in child array by finding matching id using the recursive function. For example, if want to add JSON object at id==1; then it was possible by using for loop but what if I want to add JSON object at id==22 or id==221.

I am trying using below code

var body = '';

function scan(obj)
{
  var k;
  if (obj instanceof Object) {
    for (k in obj){
        if (obj.hasOwnProperty(k)){
            body += 'scanning property ' + k + '<br/>';
            scan( obj[k] );  
        }                
    }
  } else {
    body += 'found value : ' + obj + '<br/>';
  };
 };

 scan(testJSON);

 document.getElementById('output').innerHTML = body;
Sau_Patil
  • 358
  • 3
  • 13
  • Your `testJSON` variable [isn't](https://stackoverflow.com/questions/8294088/javascript-object-vs-json) [JSON](https://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it) – VLAZ Oct 26 '18 at 12:23

2 Answers2

2

You could use an iteration with a check and return the object, if found.

function getObject(array, id) {
    var object;
    array.some(o => object = o.id === id && o || getObject(o.child || [], id));
    return object;
}

var data = [{ name: "USER1", id: 1, child: [] }, { name: "USER2", id: 2, child: [{ name: "USER2_CHILD1", id: 21, child: [] }, { name: "USER2_CHILD2", id: 22, child: [{ name: "USER2_CHILD2_CHILD1", id: 221, child: [] }] }] }, { name: "USER3", id: 3, child: [{ name: "USER3_CHILD1", id: 31, child: [] }] }];

console.log(getObject(data, 1));
console.log(getObject(data, 21));
console.log(getObject(data, 221));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Try this function, you need to parse JSON before

function insertRecord(id,dataToInsert,jsonInput){

    let checkIndex = function (arrayElement){
        return arrayElement.id === id;
    }

    let index = jsonInput.findIndex(checkIndex);

    if(index != -1) {
     if(jsonInput[index].child) {
        jsonInput[index].child.push(dataToInsert);
     }
     else {
        jsonInput[index].child = [dataToInsert];
     }
    }
    else {

      jsonInput.forEach(function(arrEle, eleIndex){
        if(arrEle.child) {
        insertRecord(id,dataToInsert,arrEle.child);
        }
      });
    }
}

insertRecord(22,{
  'name':'USER1',
  'id':33,
  'child':[],
},testJSON);