这个数据结构如何修改

22edb4628d77e56d8b78742821a7e24.png
想把这个数据结构修改成下面的数据结构应该如何修改?
095e81fccaebdf4773829f19b053b46.png

这是数据

        let arr1 = [
          {
            name: '12421412',
            ids: ['erqre']
          },
          {
            name: '12421412',
            ids: ['werwer']
          },
          {
            name: '12421412',
            ids: ['wetweew']
          },
            {
              name: '12421413',
              ids: ['wetweew']
            },
          {
            name: '12421413',
            ids: ['wetweew']
          },
          {
            name: '12421413',
            ids: ['wetweew']
          }
          ]
阅读 2.5k
4 个回答
arr1 = arr1.reduce((acc, cur) => {
  let index = acc.findIndex(ele => cur.name === ele.name);
  if(-1 === index){
    acc.push(cur);
  }else{
    acc[index].ids = acc[index].ids.concat(cur.ids);
  }
  return acc;
}, []);
let arr = [
  {
    name: '12421412',
    ids: ['erqre']
  },
  {
    name: '12421412',
    ids: ['werwer']
  },
  {
    name: '12421412',
    ids: ['wetweew']
  },
  {
    name: '12421413',
    ids: ['wetweew']
  },
  {
    name: '12421413',
    ids: ['wetweew']
  },
  {
    name: '12421413',
    ids: ['wetweew']
  }
];

const map = new Map();

arr.forEach(obj => {
  const ids = map.get(obj.name);
  if (ids === undefined) {
    map.set(obj.name, obj.ids);
  } else {
    ids.push(obj.ids[0]);
    map.set(obj.name, ids);
  }
});

const result = [];

map.forEach((v, k) => {
  result.push({
    name: k,
    ids: v
  });
});

console.log(result);

emmm 感觉写得有点麻烦

感觉写的也不怎么样

        const set = new Set();
        arr1.forEach(item => {
            set.add(item.name);
        });
        const result = [];
        set.forEach(item => {
            const obj = {
                name: item,
                ids: []
            };
            const test = arr1.forEach(el => {
                if (el.name === item) {
                    obj.ids.push(el.ids);
                }
            })
            result.push(obj);
        });
        console.log(result);
function merge(arr1){
  var cache = [], //记录name
     newArr = []; 
  for(var i=0;i<arr1.length;i++){
   var oN = arr1[i].name,
       idx = cache.indexOf(oN); //根据cache中的下标对应新数组的下标
   if(idx == -1){
     cache.push(oN);
     newArr.push(arr1[i]);
   }else
     newArr[idx].ids = newArr[idx].ids.concat(arr1[i].ids);
  }
 return newArr;
}
merge(arr1);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏