我有一個現有的物件陣列,它們共享一個標題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']
uj5u.com熱心網友回復:
將陣列縮減為 Map,使用type為鍵。用于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)
另一種選擇是將陣列簡化為組的映射[type, object],然后用于Array.from()將映射的條目轉換為所需的形式(TS 操場):
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462019.html
標籤:javascript 数组 打字稿 循环
上一篇:如何將此回圈轉換為串列理解?
