user3378165
user3378165

Reputation: 6896

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
}

Upvotes: 0

Views: 51

Answers (1)

Bergi
Bergi

Reputation: 664247

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.

Upvotes: 2

Related Questions