reactjs 从对象数组中提取相似项并创建新数组的不同方法

xuo3flqw  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(170)

我想从一个对象数组中提取相似的值,并创建一个新的数组,但格式不同。所以我可以做到这一点,但我认为代码有点长。当然,将有更少的代码来做这一点。所以有人知道任何其他的方式来做这一点,也许是一个正确的方式来做这一点?提前感谢。

const data = [
  {
    id: 1,
    type: 'easy',
    name: 'type 1',
    class: 12
  },
  {
    id: 2,
    type: 'easy',
    name: 'type 2',
    class: 10
  },
  {
    id: 3,
    type: 'medium',
    name: 'type 3',
    class: 12
  },
  {
    id: 4,
    type: 'hard',
    name: 'type 4',
    class: 10
  },
  {
    id: 5,
    type: 'medium',
    name: 'type 5',
    class: 10
  },

  {
    id: 6,
    type: 'easy',
    name: 'type 2',
    class: 10
  },
  {
    id: 7,
    type: 'medium',
    name: 'type 3',
    class: 12
  },
  {
    id: 8,
    type: 'hard',
    name: 'type 4',
    class: 10
  },
  {
    id: 9,
    type: 'medium',
    name: 'type 5',
    class: 10
  },
  {
    id: 10,
    type: 'hard',
    name: 'type 4',
    class: 10
  },
]
const dataNeeded = [];

data.forEach(dataItem => {
  if(dataNeeded.length) {
    const isExist = dataNeeded.find(dataNeededItem => dataNeededItem.type === dataItem.type);
    if(isExist) {
        dataNeeded.forEach((dataNeededItem, index) => {
            if(dataNeededItem.type === dataItem.type) {
                dataNeeded[index].tests.push(dataItem)
            }
        })
    } else {
        dataNeeded.push({
          type: dataItem.type,
          tests: [dataItem]
        })
    }
  } else {
    dataNeeded.push({
      type: dataItem.type,
      tests: [dataItem]
    })
  }
})

console.log(dataNeeded);
velaa5lx

velaa5lx1#

你可以很容易地做同样的事情,只要先使用一个Map,然后把这个Map转换成一个数组。

const data=[{id:1,type:'easy',name:'type 1',class:12},{id:2,type:'easy',name:'type 2',class:10},{id:3,type:'medium',name:'type 3',class:12},{id:4,type:'hard',name:'type 4',class:10},{id:5,type:'medium',name:'type 5',class:10},{id:6,type:'easy',name:'type 2',class:10},{id:7,type:'medium',name:'type 3',class:12},{id:8,type:'hard',name:'type 4',class:10},{id:9,type:'medium',name:'type 5',class:10},{id:10,type:'hard',name:'type 4',class:10}];

const map = new Map();

data.forEach((datum) => {
    // add to map if it doesn't exist yet
    if (!map.has(datum.type)) map.set(datum.type, []);
    // push to the right type
    map.get(datum.type).push(datum);
});

// transform map into array
const dataNeeded = Array.from(map).map(([type, tests]) => ({ type, tests }));

console.log(dataNeeded);

相关问题