0

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 ]
Camilo
  • 6,504
  • 4
  • 39
  • 60
manish thakur
  • 760
  • 9
  • 35
  • 76

2 Answers2

3

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);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
0

You just need to return the li in your map callback:

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

I'm not sure what do you need but I think res should not be an array:

const res = {
  "nestedId": 11,
  "nestedData": "I am fine"
};
Camilo
  • 6,504
  • 4
  • 39
  • 60