所以我有一个对象数组,例如:
let arrayOfObjects = [
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Carrot",
Type: "Vegetable"
}
];
我需要检查它,找到重复项并为每个重复项只返回一个对象,但重复项的数量作为新参数。
像这样:
let newArrayOfObjects = [
{
Name: "Apple",
Type: "Fruit",
times: 3,
},
{
Name: "Carrot",
Type: "Vegetable",
times: 4,
}
];
我可以根据一个参数计算重复对象的数量,但我不知道如何根据整个对象进行计算。解决这个问题的最佳方法是什么?
最佳答案
您可以在原始数组上结合使用 .map
并使用 .find
搜索新形成的数组的项目。
let arrayOfObjects = [
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Carrot",
Type: "Vegetable"
}
];
const resultArray = [];
arrayOfObjects.map(item => {
//for each item in arrayOfObjects check if the object exists in the resulting array
if(resultArray.find(object => {
if(object.Name === item.Name && object.Type === item.Type) {
//if the object exists iterate times
object.times++;
return true;
//if it does not return false
} else {
return false;
}
})){
} else {
//if the object does not exists push it to the resulting array and set the times count to 1
item.times = 1;
resultArray.push(item);
}
})
console.log(resultArray)
更新:
最好使用.reduce
而不是.map
因为后者主要用于对数组的每个元素应用某个函数并得到一个函数数组执行结果。
Array .reduce()
方法也在每个项目上执行一个函数(回调),但它将结果从一个元素数组传递到另一个元素数组。因此,我们可以使用一个空数组作为开始,并用一个对象填充它或迭代 .times
属性,以防当前元素存在于传递给每个回调的累积数组中。
这是一个例子:
let arrayOfObjects = [
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Carrot",
Type: "Vegetable"
},
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Apple",
Type: "Fruit"
},
{
Name: "Carrot",
Type: "Vegetable"
}
];
const newArrayOfObjects =
arrayOfObjects.reduce((accumulator, object) => {
if(objectFound = accumulator.find(arrItem => arrItem.Name === object.Name && arrItem.Type === object.Type)) {
objectFound.times++;
} else {
object.times = 1;
accumulator.push(object);
}
return accumulator;
}, []);
console.log(newArrayOfObjects);
关于javascript - 在数组中查找重复对象并返回新的对象数组,其中重复项数作为新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58754685/