Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

json - Javascript Filter Object

I'm mapping over an array that comes with objects containing items. Each item has it's category. I would like to generate an array of categories each one bringing it's items. Here is the approach that I took so far:

...Typescript
    categories.map((item: Items) => {
        response.push({ title: item.category });
    });
...
[
  {
    category: 'Food',
    name: 'Some food1'
  },
  {
    category: 'Food',
    name: 'Some food2'
  },
  ...
]

The result must be like this:

[
  {
    title: 'Food',
    items: [
      {
        name: 'Some food1'
      },
      {
        name: 'Some food2'
      },
      ...
    ]
  },
  ...
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The most efficient way would be to write a custom function, but the easiest way would be to use Lodash's groupBy

import { groupBy } from 'lodash'

const arr = [
  {
    category: 'Food',
    name: 'Some food1'
  },
  {
    category: 'Food',
    name: 'Some food2'
  },
]

const groups = groupBy(arr, 'category')
// returns {
//   Food: [
//     { category: 'Food', name: 'Some food1' },
//     { category: 'Food', name: 'Some food2' },
//   ]
// }

const groupedArr = Object.entries(groups).map(([title, items]) => ({ title, items }))
// returns [
//   {
//     title: 'Food',
//     items: [
//       { category: 'Food', name: 'Some food1' },
//       { category: 'Food', name: 'Some food2' },
//     ]
//   },
// ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...