你瞅啥呢

2023-10-24 react+ts 遍历双重对象嵌套数组

 今天晚上发现ts中无法用forEach遍历对象嵌套数组的数据,比如typeof arr 为 object,就只能用for in 或者Object.entries 再或者Object.keys。

我这里用的是for in:

useEffect(() => {
    if (value) {
      const arr: any = [];
      for (const key in value) {
        const obj: any = {
          key: value[key].id,
          title: value[key].name,
          children: [],
        };
        const childrenObj = value[key].children
        for (const key2 in childrenObj) {
          const obj2: any = {
            key: childrenObj[key2].id,
            title: childrenObj[key2].name,
            children: [],
          }; 
          obj.children.push(obj2);
        }
        arr.push(obj);
      }
      console.log("arr ==>", arr);
      setTreeData(arr);
    }
  }, [value]);

注意🔺: 不要写成这样👇

useEffect(() => {
    if (value) {
      const arr: any = [];
      for (const key in value) {
        const obj: any = {
          key: value[key].id,
          title: value[key].name,
          children: [],
        };
        for (const key2 in value[key].children) {
          const obj2: any = {
            key: value[key2].id,
            title: value[key2].name,
            children: [],
          }; 
          obj.children.push(obj2);
        }
        arr.push(obj);
      }
      console.log("arr ==>", arr);
      setTreeData(arr);
    }
  }, [value]);

上面的第二重循环中没有把children拿出来,而是直接用第一层来遍历数据 for( const key2 in value[key].children ),这将导致无法拿到全部第二层(children)的数据!

value的数据结构:

  const value = [
    {
      title: 'title1',
      key: 1,
      childern: [
        {
          title: 'title11',
          key: 11,
          childern: []
        }
      ]
    },
    {
      title: 'title2',
      key: 2,
    }
  ]

 for in 从第二层循环开始就要暂存上一层的数据!!

 

posted @ 2023-10-24 20:06  叶乘风  阅读(251)  评论(0)    收藏  举报