美好的一天開發人員我想知道如何將一組具有不同值的物件分組到特定的子組中,在每個子組中,我根據查詢的鍵包含具有特定值的物件。
我的陣列將是這樣的
const cars =
[ { make: 'audi', model: 'r8', year: '2012' }
, { make: 'audi', model: 'rs5', year: '2013' }
, { make: 'ford', model: 'mustang', year: '2012' }
, { make: 'ford', model: 'fusion', year: '2015' }
, { make: 'kia', model: 'optima', year: '2012' }
]
我想通過鍵make在名稱的子組中收集鍵中具有作為值的2nd_class所有物件,或者將其他
物件收集在一個組中,結果是一個物件,例如:makekiaford1rst_class
const expected =
[ '2nd_class':
[ { make: 'ford', model: 'mustang', year: '2012' }
, { make: 'ford', model: 'fusion', year: '2015' }
, { make: 'kia', model: 'optima', year: '2012' }
]
, '1rst_class' :
[ { make: 'audi', model: 'r8', year: '2012' }
, { make: 'audi', model: 'rs5', year: '2013' }
]
]
網路上的所有示例總是指按鍵和一個特定值分組......任何幫助都會很棒。
uj5u.com熱心網友回復:
你需要做這樣的事情:
const cars = [
{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
// Used car make
const usedMake = [];
// Return object
const formattedObject = {
'1st_class': [],
'2nd_class': []
};
// Iterate through your car array
cars.forEach(car => {
// Check if this is the first time we see this make and process
if (usedMake.indexOf(car.make) === -1) {
// Retrieve the cars with the same make as our iterated car
const filteredCars = cars.filter(c => c.make === car.make);
if (['kia', 'ford'].includes(car.make)) {
// push in our 2nd class - we push the retrieved objects
formattedObject['2nd_class'].push(...filteredCars)
} else {
// push in our 1st class - we push the retrieved objects
formattedObject['1st_class'].push(...filteredCars)
}
// Store the used car make so we don't reuse it later
usedMake.push(car.make);
}
});
console.log(formattedObject)
該種工藝的迭代,校驗值未使用的,程序中如果未使用,儲存,防止再利用是一個基本的programmation演算法。
uj5u.com熱心網友回復:
這邊走 :
const cars =
[ { make: 'audi', model: 'r8', year: '2012' }
, { make: 'audi', model: 'rs5', year: '2013' }
, { make: 'ford', model: 'mustang', year: '2012' }
, { make: 'ford', model: 'fusion', year: '2015' }
, { make: 'kia', model: 'optima', year: '2012' }
]
const Class2 = [ 'ford', 'kia' ]
const expected = cars.reduce( (r,c) =>
{
let cls = Class2.includes(c.make) ? '2nd_class':'1rst_class'
r[cls].push({...c})
return r
} , {'2nd_class':[],'1rst_class':[] } )
console.log( expected )
.as-console-wrapper {max-height: 100%!important;top:0 }
uj5u.com熱心網友回復:
我決定嘗試創建一個通用的分組函式,而不是為您的特定情況撰寫一次性解決方案。因為您要嘗試分組,而不僅僅是通過單個值(實用程式對事物進行分組的常用方式),所以這種型別的分組功能需要更多的輸入。
所以,我創建了這個函式:
groupBy(arr, propToGroup, mapping)
它使用要分組的物件陣列、要檢查分組的這些物件中的屬性以及告訴您該屬性的哪些值屬于哪個組名稱的映射物件。
這是您可以在代碼段中運行的版本:
function groupBy(arr, propToGroup, mapping, defaultMapping) {
let output = new Map();
for (let item of arr) {
// get value of our property of interest
let val = item[propToGroup];
if (val === undefined) {
if (defaultMapping) {
val = defaultMapping;
} else {
throw new Error(`No value for property .${propToGroup} and no defaultMapping`);
}
}
let classification = mapping.get(val);
if (!classification) {
if (!defaultMapping) {
throw new Error(`Property value ${val} is not present in mapping and no defaultMapping`);
}
classification = defaultMapping;
}
let classificationArray = output.get(classification);
// if classification not found yet, then initialize as empty array
if (!classificationArray) {
classificationArray = [];
output.set(classification, classificationArray);
}
classificationArray.push(item);
}
// convert to output format
let result = [];
for (let [key, val] of output) {
result.push({
[key]: val
});
}
return result;
}
const cars = [
{ make: 'audi', model: 'r8', year: '2012' },
{ make: 'audi', model: 'rs5', year: '2013' },
{ make: 'ford', model: 'mustang', year: '2012' },
{ make: 'ford', model: 'fusion', year: '2015' },
{ make: 'kia', model: 'optima', year: '2012' },
{ make: 'vw', model: 'bug', year: '1960' },
];
const mapping = new Map([
['audi', '1rst_class'],
['ford', '2nd_class'],
['kia', '2nd_class']
]);
let result = groupBy(cars, "make", mapping, "other");
console.log(result);
這個想法是你也可以groupBy()在其他情況下重用這個函式。如果在映射中找不到給定的屬性值并且傳遞了 defaultMapping,那么它將被放入 defaultMapping 存盤桶中。如果沒有傳遞 defaultMapping 并且它不在映射中,它將拋出例外。
請注意,defaultMapping 添加了許多代碼行,但會嘗試處理意外資料或資料的情況,您需要一個“catchall”存盤桶來捕獲映射中不特定的所有其他內容。這顯然不是您的特定問題所必需的,但可能會使這對其他情況更普遍有用。
功能說明:
創建一個供內部使用的 Map 物件,以跟蹤遇到的組,其中組名是鍵,該組中的物件陣列是條目的值。
遍歷物件陣列。
獲取物件感興趣的屬性值。
如果該屬性不存在,則嘗試使用默認映射
如果該屬性確實存在,請在映射中查找它以獲取其分類。
如果沒有找到分類,嘗試使用 defaultMapping
在我們的臨時輸出 Map 中查找分類
如果未找到,則為此分類創建空陣列。
將專案添加到分類陣列
完成對陣列的迭代后,將內部 Map 物件轉換為所需的最終陣列結構并回傳它。
uj5u.com熱心網友回復:
或者你可以簡單地這樣做:
const cars = [
{ make: 'audi', model: 'r8', year: '2012' },
{ make: 'audi', model: 'rs5', year: '2013' },
{ make: 'ford', model: 'mustang', year: '2012' },
{ make: 'ford', model: 'fusion', year: '2015' },
{ make: 'kia', model: 'optima', year: '2012' }
];
const cars_in_classes=cars.reduce((a,c)=>{
const cls=(c.make==="audi"?"1st":"2nd") "_class";
(a[cls]=a[cls]||[]).push(c);
return a;}, {} );
console.log(cars_in_classes);
該行(a[cls]=a[cls]||[]).push(c);檢查物件屬性是否a[cls]已存在,如果不存在,則在將當前元素推送到其上之前將其創建為空陣列。
如果您認為有幾個品牌是“1st_class”,您可以將第 2 行更改為:
const cls=(["audi","mercedes"].indexOf(c.make)>-1?"1st":"2nd") "_class";
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395617.html
標籤:javascript 数组 ecmascript-6 javascript对象
下一篇:如何在C#中連接二維陣列中的索引
