我正在嘗試比較一組物件。每個物件都有相同的鍵,但每個鍵的值不同。我想創建一個函式來比較每個物件的相似鍵值對。
我只關心每個物件的質量和位置鍵,我想將所有物件與這兩個鍵進行比較。
例如,如果物件陣列中的第一個和第二個物件包含兩個鍵的相同值,我想創建一個輸出物件陣列來總結每個分組。
解釋:物件一和二包含相同的quality和值location。由于第三個物件沒有,因此應該創建一個新物件來匯總來自第一個和第二個物件的資訊。該新物件應包含所有水果名稱的陣列和所有標簽的陣列。輸出物件如下所示。
// Input
data = [
{
id: '1',
fruit: 'granny smith',
quality: 'good',
location: 'chicago',
tags: ['green', 'sweet'],
},
{
id: '2',
fruit: 'Fuji',
quality: 'good',
location: 'chicago',
tags: ['red', 'tart'],
},
{
id: '3',
fruit: 'gala',
quality: 'bad',
location: 'san diego',
tags: ['tall', 'thin'],
},
];
// Function
function compareObjects(arr) {
const grouped = [];
// Loop over every fruit
const similarObjects = arr.filter((obj, id) => {
// create structure for each common object
let shape = {
id,
fruits: [],
quality: '',
tags: [],
};
arr.forEach((item) => {
// Return a new shape object that contains all fruit names, tags, and quality
if (item.quality == obj.quality && item.location == obj.location) {
shape.id = id;
shape.fruits.push(item.fruit);
shape.fruits.push(obj.fruit);
shape.quality = item.quality;
shape.tags.push(item.tag);
shape.tags.push(obj.tag);
return shape;
}
});
return obj;
});
return similarObjects;
}
console.log(compareObjects(data));
// Output
const output = [
{
id: 'a',
fruits: ['grann smith', 'fuji'],
quality: 'good',
tags: ['green', 'sweet', 'red', 'tart'],
},
...
];
uj5u.com熱心網友回復:
您可以data按它們分組,quality并location使用Array.prototype.reduce并過濾長度大于一的組。
const
data = [
{ id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] },
{ id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] },
{ id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] },
],
output = Object.values(
data.reduce((r, d) => {
const key = `${d.quality} ${d.location}`;
if (!r[key]) {
r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] };
}
r[key].fruits.push(d.fruit);
r[key].tags.push(...d.tags);
return r;
}, {})
).filter((d) => d.fruits.length > 1);
console.log(output);
如果您還希望只保留唯一的水果,那么您可以映射結果陣列并使用Set.
顯示代碼片段
const
data = [
{ id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] },
{ id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] },
{ id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] },
],
output = Object.values(
data.reduce((r, d) => {
const key = `${d.quality} ${d.location}`;
if (!r[key]) {
r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] };
}
r[key].fruits.push(d.fruit);
r[key].tags.push(...d.tags);
return r;
}, {})
)
.filter((d) => d.fruits.length > 1)
.map((d) => ({ ...d, fruits: [...new Set(d.fruits)] }));
console.log(output);
其他相關檔案:
- 傳播語法 (...)
- Array.prototype.push
- Array.prototype.filter
- 物件值
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481225.html
標籤:javascript 数组 算法 目的 比较
