簡體   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