javascript - 如何在嵌套对象中推送响应
问题描述
我有一个嵌套数据,我试图在其中推送我从服务器获得的响应,
我的数据是:
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 ]
解决方案
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);
推荐阅读
- python - SQLAlchemy OperationalError 没有这样的表
- android - Nativescript Android:拍照后frame.navigate不起作用
- nested - 嵌套 N1QL 更新查询
- python - 如何通过守护线程从同步代码中使 asyncpg 驱动程序工作?
- powershell - 如何在 Powershell 的组中找到所有嵌套的 Active Directory 组?
- amazon-s3 - Heroku 到 AWS S3 存储桶的连接时间
- javascript - 从 div 获取格式化文本到 PHP 变量
- firebase - 我的应用程序将用户设备型号发送到 Firestore。这是否违反任何 App Store 或 Play Store 政策?
- ios - 加载数据后如何从完成块中获取整个数组
- php - 如何显示点赞帖子的人数?