Search code examples
javascriptecmascript-6ecmascript-2016

How to push response in nested onject


I have a nested data inside which I am trying to push my response I am getting from the server,

My data is :

let d = [{
    "dashId": 3,
    "dashName": "one",
    "dashData": []
  },
  {
    "dashId": 4,
    "dashName": "two",
    "dashData": [{
      "nestedId": 1,
      "nestedData": "how are you"
    }]
  }
]

This the data below I want to push

let res = [{
  "nestedId": 11,
  "nestedData": "I am fine"
}]

What I am doing is:-

let dd = d.map(li => {
  if (li.dashId === 3) {
    li.dashData.push(res)
  }
})

console.log(dd)

I am getting output as undefined

[ undefined, undefined ]

Solution

  • Array.map function creates a new array populated with the results of calling a provided function on every element in the calling array. So the callback inside map should return an item and on your code, nothing is returned on callback.

    In your case, it's better to use Array.forEach as follows.

    const d = [{
        "dashId": 3,
        "dashName": "one",
        "dashData": []
      },
      {
        "dashId": 4,
        "dashName": "two",
        "dashData": [{
          "nestedId": 1,
          "nestedData": "how are you"
        }]
      }
    ];
    
    const res = [{
      "nestedId": 11,
      "nestedData": "I am fine"
    }];
    
    d.forEach(li => {
      if (li.dashId === 3) {
        li.dashData.push(...res)
      }
    });
    
    console.log(d);