有誰知道如何通過物件鍵對物件陣列進行分組,然后根據分組創建一個新的物件陣列?例如,我有一個如下所示的 Build 物件陣列,我想按產品分組并基于此創建另一個顏色和價格物件。
build = [
{
'Product': 'Cabinets',
'Color': 'Blue',
},
{
'Product': 'CounterTop',
'Color': 'White',
},
{
'Product': 'Cabinets',
'Color': 'Yellow',
},
{
'Product': 'Cabinets',
'Color': 'Yellow',
}
]
我想要這樣
[
{
'Product':'Cabinet',
'color' : { 'Blue','Yellow' }
},
{
'Product':'CounterTop',
'color' : { 'White' }
}
]
我寫了一個代碼來存檔它,但我沒有得到預期的結果。
build.forEach(pr => {
if (pr.Product in result) {
result[pr['Product']]['Color'] = pr['Color'];
}
else {
result[pr['Product']] = {
'Product': pr['Product'],
'Color': pr['Color']
}
}
});
上面的代碼回傳
[
{
'Product':'Cabinet',
'color' : 'Yellow'
},
{
'Product':'CounterTop',
'color' : 'White'
}
]
uj5u.com熱心網友回復:
期望'color' : { 'Blue','Yellow' }輸出是錯誤的。物件是資料的鍵值對。
相反,您想color成為一個陣列。我調整了你的代碼:
build.forEach(pr => {
if (pr.Product in result) {
result[pr['Product']]['Color'].push(pr['Color']);
} else {
result[pr['Product']] = {
'Product': pr['Product'],
'Color': [pr['Color']]
}
}
});
現在考慮如何防止陣列中出現重復值。@Lissy93 的回答通過使用findIndex.
uj5u.com熱心網友回復:
這是一個作業版本。希望能幫助到你 :)
const builds = [
{ 'Product': 'Cabinets', 'Color': 'Blue' },
{ 'Product': 'CounterTop', 'Color': 'White' },
{ 'Product': 'Cabinets', 'Color': 'Yellow' },
{ 'Product': 'Cabinets', 'Color': 'Yellow' }
];
const results = [];
builds.forEach((build) => {
const index = results.findIndex((b) => b.Product === build.Product);
if (index === -1) {
results.push({Product: build.Product, Color: [ build.Color ]});
} else {
results[index] = {Product: build.Product, Color: [ ...results[index].Color, build.Color ]}
}
});
console.log(results);
您的代碼中的主要問題是,您將color. KVP 看起來像{ color: 'red' },而陣列是:[ 'red', 'blue']。
uj5u.com熱心網友回復:
使用此策略:
- 尋找獨特的產品
- 基于獨特的產品使用
Array#map和Array#filter構建所需的資料
請參閱下面的演示:
const builds = [ { 'Product': 'Cabinets', 'Color': 'Blue' }, { 'Product': 'CounterTop', 'Color': 'White' }, { 'Product': 'Cabinets', 'Color': 'Yellow' }, { 'Product': 'Cabinets', 'Color': 'Yellow' } ],
output = [...new Set(builds.map(({Product}) => Product))]
.map(Product =>
({
Product,
Color:builds.filter(({Product:P}) => P === Product)
.map(({Color}) => Color)
})
);
console.log(output);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/467427.html
標籤:javascript 数组 分组
