js 问题出在哪里? 附 demo

题目描述

exceptId === id 将checked设为false 关联 父级
子项 全为 false,父级则为false

题目来源及自己的思路

/**
     * 方法
     * 层级 N层级
     * 结果:返回新的数组对象 - exceptId === id 将checked设为false 关联 父级
     * 
    */
    function resetData(list, exceptId) {
      if (Array.isArray(list) && list.length !== 0) {
        list = list.map(item => {
          if (item.key === exceptId) {
            item.checked = false;
            if (!item.isLeaf) {
              item.children = item.children.map(it => it = { ...it, checked: false });
            }
          } else if (!item.isLeaf) {
            resetData(item.children, exceptId);
          }
          return item;
        });
        return list;
      } else {
        return false;
      }
    }

相关代码

粘贴代码文本(请勿用截图)

const arr = [
      {
        "id": 3,
        "name": "标题1",
        "children": [
          {
            "id": 4,
            "name": "1-1",
            "children": null
          }
        ]
      },
      {
        "id": 5,
        "name": "标题2",
        "children": [
          {
            "id": 6,
            "name": "2-1",
            "checked": true,
            "children": null
          },
          {
            "id": 7,
            "name": "2-2",
            "children": null
          }
        ]
      },
      {
        "id": 8,
        "name": "标题3",
        "children": [
          {
            "id": 9,
            "name": "3-1",
            "checked": true,
            "children": null
          }
        ]
      }
    ];

你期待的结果是什么?实际看到的错误信息又是什么?

resetData(arr, 6)
阅读 1.1k
1 个回答

item.key 换成 item.id,因为你传入的是 id,而且你的数据结构里没有 key。

image.png


it => it = { ...it, checked: false }

还有这一句,报错了。然后我修改了一下 item.children = item.children?.map(it => ({ ...it, checked: false })); 不太清楚你为什么要这样写。


别滑走,还有错误的地方。你这个其实把原数据也改了。你map的时候应该把item拷贝一份再去操作。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题