Bootstrap

js对象数组拍平(扁平化)

实现目标:

  • 将多层嵌套children的对象数组拍平,并存入父元素的id(可替换)。

实现方法:

  • 1.储存第一层数组对象

  • 2.查看数组对象内是否有children,若有children则递归,并存入父元素的key。

测试数据:

  let Data = [
        {
          id: 1,
          content: '是否是双方都',
          list: [
            {
              id: 2,
              content: 'sof决定受理咖啡机离开',
              list: [
                {
                  id: 3,
                  content: '水电费',
                  list: [],
                },
              ],
            },
          ],
        },
        {
          id: 4,
          content: 'sof决定受理咖啡机离开',
          list: [
            {
              id: 5,
              content: '测试5',
              list: [],
            },
          ],
        },
        {
          id: 6,
          content: '测试6',
          list: [],
        },
      ];

js代码:

  const flatData = (data, parentId = undefined) => {
        return data.reduce((prev, curr) => {
          if (parentId != undefined) {
            Object.assign(curr, {
              parentId: parentId,
            });
          }
          prev.push(curr);
          if (curr.list.length > 0) {
            prev.push(...flatData(curr.list, curr.id));
          }
          return prev;
        }, []);
      };

let flated = flatData(Data);
console.log(flated);
;