首页 > 解决方案 > 如何在嵌套对象中推送响应

问题描述

我有一个嵌套数据,我试图在其中推送我从服务器获得的响应,

我的数据是:

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

这是下面我要推送的数据

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

我正在做的是: -

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

console.log(dd)

我得到未定义的输出

[ undefined, undefined ]

标签: javascriptecmascript-6ecmascript-2016

解决方案


Array.map函数创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。所以里面的回调map应该返回一个项目,在你的代码上,回调没有返回任何内容。

在您的情况下,最好Array.forEach按以下方式使用。

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);


推荐阅读