简体   繁体   English

重构对象数组

[英]Restructure objects array

I have an objects array:我有一个对象数组:

[{description: a, category: a},{description: b, category: b},{description: c, category: c}...]

I need to restructure it to this format:我需要将其重组为这种格式:

[{category: a, items: [a, b, c, d], priority: 1},{category: b, items: [a, b, c, d], priority: 2},{category: c, items: [a, b, c, d], priority: 10}]

What I did below works and returns the desired result, I'm just wondering if there is a way to shorten it.我在下面所做的工作并返回所需的结果,我只是想知道是否有办法缩短它。

const getNewList = items => {
// Filter items to get all categories and set their priority
  let categories: any = [
    ...new Set(
      items.map(item => {
        switch (item.category.toLowerCase()) {
          case 'a':
            return {category: item.category, priority: 1}
          case 'b':
            return {category: item.category, priority: 2}
          case 'c':
            return {category: item.category, priority: 10}
        }
      })
    )
  ]

// Remove duplicate entries
  categories = [
    ...new Map(categories.map(item => [item.category, item])).values()
  ]

// Restructure object - get all items and the priority grouped by category
  const newList = []
  for (var i = 0; i < categories.length; i++) {
    newList.push({
      category: categories[i],
      items: items
        .filter(item=> item.category === categories[i].category)
        .map(item=> {
          return item.description
        }),
      priority: categories[i].priority
    })
  }
  return newList
}

You might be looking for您可能正在寻找

function getNewList(items) {
  const categories = new Map([
    ['a', {category: 'a', items: [], priority: 1}],
    ['b', {category: 'b', items: [], priority: 2}],
    ['c', {category: 'c', items: [], priority: 10}],
  ]);
  for (const item of items) {
    categories.get(item.category.toLowerCase()).items.push(item.description);
  }
  return Array.from(categories.values());
}

If you don't want to have empty categories, you can .filter(c => c.items.length) them out.如果你不想有空的类别,你可以.filter(c => c.items.length)它们出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM