Search code examples
javascriptmultidimensional-arraycallbacknested

nested array call back function


I have a nested object as below, where array is returned as object using results key.

var testList = {
  results: [
    {
      id: 1,
      testList: {
        results: [
          {
            id: 11,
            testList: {}
          }
        ]
      }
    },
    {
      id: 2,
      testList: {}
    }
  ]
};

I want a resultset as below, where direct array is returned instead of object of array. Please help!

var testList = [
  {
    id: 1,
    testList: [
      {
        id: 11,
        testList: {}
      }
    ]
  },
  {
    id: 2,
    testList: {}
  }
];

Solution

  • var testList = {
    results: [
      {
        id: 1,
        testList: {
          results: [
            {
              id: 11,
              testList: {}
            }
          ]
        }
      },
      {
        id: 2,
        testList: {}
      }
     ]
    };
    
    console.log("Original:")
    console.log("var testList =",JSON.stringify(testList, null, 2))
    
    
    let tempList = []
    if(testList.results){
      for(let i = 0; i < testList.results.length; i++){
        let r = testList.results[i]
        let newEntry = {
          id: r.id,
          testList: []
        }
        if(r.testList.results){
          for(let j = 0; j < r.testList.results.length; j++){
            newEntry.testList.push(r.testList.results[j])
          }
        } else {
          newEntry.testList = {}
        }
        tempList.push(newEntry)
       }
     testList = tempList;
    }
    console.log("Modified:")
    console.log("var testList =",JSON.stringify(testList, null, 2))
    

    or if the testList if going to be infinite nested levels deep you can do it recursively like this:

    function flattenResults(list){
      let newList = []
      if(list.results){
        for(let i = 0; i < list.results.length; i++){
          let r = list.results[i]
          let newEntry = {
            id: r.id,
            testList: []
          }
          if(r.testList.results){
            newEntry.testList = flattenResults(r.testList) //recursive call
          } else {
            newEntry.testList = {}
          }
          newList.push(newEntry)
         }
       }
     return newList 
    }
    
    testList = flattenResults(testList)