JS 数组对象根据某一相同key合并成新的数组

很久没写随笔了,可能太安逸了!!!

 

例子:

    let arr = [
      { name: '小明',age: 20,school: '清华' },
      { name: '小红',age: 21,school: '清华' },
      { name: '小白',age: 18,school: '北大' },
      { name: '小黄',age: 19,school: '北大' },
      { name: '小浪',age: 21,school: '哈佛' },
    ]

需求是将具有相同 “school” 的对象合并为新的数组

结果如下:

    let data = [
      {
        school: "清华",
        children: [
          { name: "小明", age: 20, school: "清华" },
          { name: "小红", age: 21, school: "清华" },
        ]
      },
      {
        school: "北大",
        children: [
          { name: "小白", age: 18, school: "北大" },
          { name: "小黄", age: 19, school: "北大" },
        ]
      },
      {
        school: "哈佛",
        children: [
          { name: "小浪", age: 21, school: "哈佛" },
        ]
      },
    ]

 

解决方案一:

    handlerDatas(arr){
      // arr 传过来的原数组  
      let tempArr = [];
      let endData = [];
      for (let i = 0; i < arr.length; i++) {
        if (tempArr.indexOf(arr[i].school) === -1) {
          endData.push({
            school: arr[i].school,
            children: [arr[i]]
          });
          tempArr.push(arr[i].school);
        } else {
          for (let j = 0; j < endData.length; j++) {
            if (endData[j].school == arr[i].school) {
              endData[j].children.push(arr[i]);
              break;
            }
          }
        }
      }
      console.log(endData); // 最终输出
    },

 

解决方案二:

    handlerDatas(arr){
      let obj = {};
      arr.forEach((item, index) => {
          let { school } = item;
          if (!obj[school]) {
              obj[school] = {
                  school,
                  children: []
              }
          }
          obj[school].children.push(item);
      });
      let data = Object.values(obj); // 最终输出
    },

 

还有其它的方案,可以自行百度。

以上解决方案借鉴了其他博主的文章

 

扩展延伸: 将数组对象改成对象数组

    let arr = [
      { name: '小明',age: 20,school: 'qinghua',},
      { name: '小红',age: 21,school: 'qinghua',},
      { name: '小白',age: 18,school: 'beida',},
      { name: '小黄',age: 19,school: 'beida',},
      { name: '小浪',age: 21,school: 'hafo',},
    ]

    handlerDatas(arr){
      let obj = {};
      arr.forEach((item, index) => {
          let { school } = item;
          if (!obj[school]) {
              obj[school] = {
            school,
                  children: []
              }
          }
          obj[school].children.push(item);
      });
      let data = Object.values(obj);
      let newData = {};

      data.forEach((item, i) => {
        let key = item.school;
        let value = item.children;
        newData[key] = value;
      });
      console.log(newData); // 最终输出
    },

 

posted @ 2020-05-25 16:46  _whys  阅读(13292)  评论(0编辑  收藏  举报