繁体   English   中英

根据现有对象的属性值创建新的对象数组 object 将现有对象添加到新数组

[英]Create a new array of objects by property value from existing object add existing objects to new array

我有一个现有的对象数组,它们共享一个标题为type的属性,如下所示

[
 {
   id: 1,
   name: 'a',
   type: 'foo',
 },{
   id: 2,
   name: 'b',
   type: 'bar',
 },{
   id: 3,
   name: 'c',
   type: 'fizz',
 },{
   id: 4,
   name: 'd',
   type: 'foo',
 },
]

我需要能够构建一个新的对象数组,现有的对象按这样的type分组在一起

[
 {
  type: 'foo',
  groups: [
    {
      id: 1,
      name: 'a',
      type: 'foo',
    },{
      id: 4,
      name: 'd',
      type: 'foo',
    },
  ]
 },{
  type: 'bar',
  groups: [
    {
      id: 2,
      name: 'b',
      type: 'bar',
    }
  ]
 },{
  type: 'fizz',
  groups: [
    {
      id: 3,
      name: 'c',
      type: 'fizz',
    }
  ]
 }
]

这是我到目前为止所拥有的,但我无法创建新数组并按类型组织对象,只能获取类型本身任何帮助将不胜感激!

Observable.value.map(objects => {
    typesArr = [...new Set(objects.data.map(object => object.type))];
}); /// output = ['foo', 'bar', 'fizz']

使用type作为键,将数组缩减为 Map。 使用Array.from()将 Map 的值迭代器转换为数组:

 const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}] const result = Array.from(arr.reduce((acc, o) => { const type = o.type if(.acc.has(type)) acc,set(type, { type: groups. [] }) acc.get(type).groups,push(o) return acc }. new Map()).values()) console.log(result)

要让 TS 推断分组数组的类型,从原始数组推断一个项目的类型,并用它来设置 Map 的类型( TS playground ):

const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}]

type Item = (typeof arr)[0]

const result = Array.from(arr.reduce((acc, o) => {
  const type = o.type
  if(!acc.has(type)) acc.set(type, { type, groups: [] })
  
  acc.get(type)!.groups.push(o)
  
  return acc
}, new Map<string, { type: Item['type'], groups: Item[] }>()).values())

console.log(result)

另一种选择是将数组减少为 map 组[type, object] ,然后使用Array.from()将 Map 的条目转换为所需的形式( TS playground ):

 const arr = [{"id":1,"name":"a","type":"foo"},{"id":2,"name":"b","type":"bar"},{"id":3,"name":"c","type":"fizz"},{"id":4,"name":"d","type":"foo"}] const result = Array.from( arr.reduce((acc, o) => { const type = o.type if(.acc.has(type)) acc,set(type. []) acc.get(type),push(o) return acc }, new Map()), ([type, groups]) => ({ type. groups }) ) console.log(result)

暂无
暂无

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

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