javascript - 如何递归地将对象键值对添加到具有子数组的对象数组中?
问题描述
我仍在学习递归的技巧,我想在这个嵌套的数组树中的每个对象中添加“isChecked:false”。
const nestedMap = (arr) => {
const result = arr.map(row => {
if (row.children.length) {
const children = row.children.map(child => {
return { ...child, isChecked: false };
});
return { ...row, isChecked: false, children };
} else {
return { ...row, isChecked: false };
}
});
return result[0].children[0]
}
nestedMap([{title: 'page1', children: [{title: 'page2', children: [{title: 'page4'}]}, {title: 'page3'}]}, {title: 'page5', children: []}])
这是我的结果 - 正如你所看到的,我成功地更新了第一组孩子,但没有更新其余的孩子。
{ title: 'page2',
children: [ { title: 'page4' } ],
isChecked: false }
我知道我应该在其内部的某个地方调用该函数,但我是个白痴。与往常一样,我们将不胜感激任何帮助。谢谢你。
解决方案
您的 if 语句if (row.children.length) {
检查是否row.children
是一个长度 > 0 的数组,所以这里是您想nestedMap
再次调用的地方。
尝试这样的事情:
const nestedMap = (arr) => {
const result = arr.map(row => {
// check if row.children exists AND if its length exists / is greater than 0
if (row.children && row.children.length) {
const children = nestedMap(row.children);
return { ...row, isChecked: false, children };
} else {
return { ...row, isChecked: false };
}
});
// Note: You should probably return the entire result here, not result[0].children[0]
return result;
}
let output = nestedMap([{title: 'page1', children: [{title: 'page2', children: [{title: 'page4'}]}, {title: 'page3'}]}, {title: 'page5', children: []}])
console.log(output)
请注意,我做了 3 处更改:
if (row.children && row.children.length) {
- 在检查之前,我添加了检查以确保
row.children
存在row.children.length
- 在检查之前,我添加了检查以确保
const children = nestedMap(row.children);
- 这是我们进行递归的地方:)
return result;
- 这将返回整个结果(原始嵌套的对象数组,
isChecked: false
每个对象中都有)。 - 注意:我不确定你为什么用 结束你的函数
result[0].children[0]
,它只会返回原始数组的第一个项目的第一个孩子?
- 这将返回整个结果(原始嵌套的对象数组,
推荐阅读
- php - 包装WordPress最新帖子链接
- c++ - C++ constexpr 函数总是在编译时评估?
- postgresql - 如何使用 dblink 将表从一个数据库传输/推送到另一个数据库
- react-native - 不变违规:requireNativeComponent:在 UIManager 中找不到“AIRMap”。- 反应原生地图
- php - 当我尝试为 base64 图像设置图像分辨率和色彩空间然后将其保存为 jpg 格式时,Imagick php 类不起作用
- lua - 这段代码是什么意思(如果 v 则返回 v 结束)?
- php - 如果用户具有角色,则将复选框标记为选中
- c# - SQLITE - IDbConnection c# .net last_insert_rowid
- asp.net-core - 将 Azure Active Directory 与 aspnetcore 应用程序一起使用
- windows - 通过QProcess调用bash.exe:kill不杀子进程