我正在尋找一個物件陣列,并根據所選物件屬性將其轉換為子陣列陣列
例如:
[
{foo: 1, bar: a}, {foo: 2, bar: b}, {foo: 1, bar: c}, {foo: 2, bar: d}
]
使用 foo 屬性創建子陣列將變為:
[
[
{foo: 1, bar: a}, {foo: 1, bar: c},
],
[
{foo: 2, bar: b}, {foo: 2, bar: d}
]
]
我想不出一個有效的方法來解決這個問題。我一直求助于創建一組我選擇的值的所有唯一屬性值,然后多次強制通過它。
const distinctProperties = [...new Set(originalArray.map(item => item.foo))]
const newArray = distinctProperties.map(item => originalArray.filter(obj => obj.foo === item))
在此先感謝您的一些建議!
uj5u.com熱心網友回復:
可以用reduce. 您可以將其包裝在另一個功能上,以按您想要的鍵進行分組。
在這里,我根據的值進行分組,foo并且res會像這樣
{
1: [{
bar: "a",
foo: 1
}, {
bar: "c",
foo: 1
}],
2: [{
bar: "b",
foo: 2
}, {
bar: "d",
foo: 2
}]
}
然后我正在接受Object.values這個來獲得你想要的陣列格式
let a =[
{foo: 1, bar: 'a'}, {foo: 2, bar: 'b'}, {foo: 1, bar: 'c'}, {foo: 2, bar: 'd'}
]
let res= Object.values(a.reduce((acc,curr)=> {
if(!acc[curr.foo])acc[curr.foo]=[];
acc[curr.foo].push(curr)
return acc;
},{}))
console.log(res)
作為以鍵名作為輸入的通用函式
let a =[
{foo: 1, bar: 'a'}, {foo: 2, bar: 'b'}, {foo: 1, bar: 'c'}, {foo: 2, bar: 'd'}
]
let groupByValue = (arr,key) => {
return Object.values(arr.reduce((acc,curr)=> {
if(!acc[curr[key]])acc[curr[key]]=[];
acc[curr[key]].push(curr)
return acc;
},{}))
}
let res1 = groupByValue(a,'foo')
let res2 = groupByValue(a,'bar')
console.log(res1)
console.log(res2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/431115.html
標籤:javascript 数组 目的 数据操作
