Search code examples
javascriptarraysecmascript-6nestednested-loops

iterating through nested array of objects


i have this object

var arr = {
  specss: [{
      moe: 1,
      spec: [{
          specID: 4,
          cat: [{
              catID: 6,
            }],
        },
        {
          specID: 11,
          cat: [{
              catID: 7,
            }],
        }],
    }],
};

I am trying to reduce it to a simpler form.

I have tried looping through them but I always get the first item in the spec not all the items inside

this is my desired output

[{
    moe: 1,
    spec: [
      {
        specID: 4,
        catID: 6,
      },
      {
        specID: 11,
        catID: 7,
      },
    ],
  }];

Solution

  • Just change arr to be arr.specss, then loop over every spec of the resulting array, moving the .catID property of the first cat object into the spec object. Like this:

    var arr = {
      specss: [{
          moe: 1,
          spec: [{
              specID: 4,
              cat: [{
                  catID: 6,
                }],
            },
            {
              specID: 11,
              cat: [{
                  catID: 7,
                }],
            }],
        }],
    };
    
    arr = arr.specss;
    for (const specs of arr) {
      for (const spec of specs.spec) {
        spec.catID = spec.cat[0].catID;
        delete spec.cat;
      }
    }
    console.log(arr)