js 树向上递归修改数据 有什么好的写法呢!

2019-09-19 00:00:27 +08:00
 coderabbit
let a = [
  {
    key: 1,
    title: '一级',
    parentKey: 0,
    status: {choose: false},
    children: [
      {
        key: 10, title: '一级-0', parentKey: 1, status: {choose: false}, children: [
          {key: 15, title: '一级-0-1', parentKey: 10, status: {choose: false}}
        ]
      },
      {key: 11, title: '一级-1', parentKey: 1, status: {choose: false}},
      {key: 12, title: '一级-2', parentKey: 1, status: {choose: false}},
      {key: 13, title: '一级-3', parentKey: 1, status: {choose: false}},
      {key: 14, title: '一级-4', parentKey: 1, status: {choose: false}}
    ]
  }
];

我想修改 key 15 每个父级 status 里的 choose 状态。 也就是 key 10 key 的 status choose 都为 true 如果是 json 对象很好找,但是已经是树形了向下好找却向上不好找!怎么更优的实现它呢!

4632 次点击
所在节点    JavaScript
11 条回复
lemontv
2019-09-19 00:33:39 +08:00
直接判断当前节点的子节点是否包括 key15
azh7138m
2019-09-19 02:02:33 +08:00
autoxbc
2019-09-19 02:17:28 +08:00
把对象展平就很容易寻址

https://codepen.io/autoxbc/pen/xxKyWmq
coderabbit
2019-09-19 09:12:05 +08:00
```
let parent = (data, obj) => {
data.forEach(item => {
if (item.key === obj.parentKey) {
item.status.choose = true;
parent(data, item);
}
if (item.children && item.children.length) {
item.status.choose = true;
parent(item.children, obj);
}
});
};
let obj = { key: 15, title: '一级-0-1', parentKey: 10, status: { choose: false } };
console.log(a);
```
coderabbit
2019-09-19 09:13:06 +08:00
@autoxbc @azh7138m 学习了
Sczlog
2019-09-19 09:17:30 +08:00
改一下数据结构,用一个表型结构来存储所有选项的数据,然后再用类似的树形结构来存储层级。
12tall
2019-09-19 09:26:18 +08:00
@autoxbc @Sczlog
学习了!
感觉有点 B+树的意思哈[这句我瞎说的]
jorneyr
2019-09-19 12:34:39 +08:00
可以获取数据后先给每个节点赋值一个 parent 对象,从下到上就好处理了:

treeWalk(node) {
for (let child of node.children) {
child.parent = node;
treeWalk(child);
}
}
dany813
2019-09-19 13:15:31 +08:00
@autoxbc 老哥的代码风格,有点迷
autoxbc
2019-09-19 14:17:36 +08:00
@dany813 #9 for 绕了点?在真值判断处赋值可能不合规范,不过很好用,也是链式查找的范式写法
dany813
2019-09-19 15:06:25 +08:00
@autoxbc 是的 for 的很骚气,看了半天,可能我比较菜吧 哈哈

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/601979

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX