js 多维数组对象转一维数组对象

flatten(arr) {
      return [].concat(...arr.map(item => {
            if (item.children) {
              let arr = [].concat(item, ...this.flatten(item.children));
              delete item.children;
              return arr;
            }
            return [].concat(item);
          }
      ));
}

let fromData = [
        {
          id: '310000',
          pid: 0,
          name: '上海',
          children: [
            {
              pid: '310000',
              id: '310100',
              name: '市辖区',
            },
            {
              pid: '310000',
              id: '310200',
              name: '郊区',
            }
          ]
        },
        {
          id: '350000',
          pid: 0,
          name: '福建省',
          children: [
            {
              pid: '350000',
              id: '350100',
              name: '厦门',
            },
            {
              pid: '350000',
              id: '350200',
              name: '泉州',
            }
          ]
        },
        {
          id: '110000',
          pid: 0,
          name: '北京',
        }
]

flatten(fromData);

  

posted @ 2021-10-08 15:12  PromiseOne  阅读(682)  评论(0编辑  收藏  举报