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);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM