我一直在努力解决我遇到的问题。我有一个包含对象的数组,如下所示:
var array = [
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Hannah Reed",
Country: "Scottland",
Age: 23
},
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Robert Landley",
Country: "England",
Age: 84
},
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Robert Landley",
Country: "England",
Age: 84
}
];
我想获取其中具有重复值的对象,并基于要搜索的值。即,我想获得具有重复值“name”和“age”但没有“country”的对象,所以我最终会得到:
[
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Robert Landley",
Country: "England",
Age: 84
},
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Robert Landley",
Country: "England",
Age: 84
}
];
如果一直在努力做
array.forEach(function(name, age){
if(array.name == name || array.age == age){
console.log(the result)
}
})
但这只会检查对象的值是否等于它们自身。
谁能帮帮我?
最佳答案
您可以使用 2 个reduce
。第一个是对数组进行分组。第二种是仅包括具有 1 个以上元素的组。
var array = [{"name":"Steven Smith","Country":"England","Age":35},{"name":"Hannah Reed","Country":"Scottland","Age":23},{"name":"Steven Smith","Country":"England","Age":35},{"name":"Robert Landley","Country":"England","Age":84},{"name":"Steven Smith","Country":"England","Age":35},{"name":"Robert Landley","Country":"England","Age":84}]
var result = Object.values(array.reduce((c, v) => {
let k = v.name + '-' + v.Age;
c[k] = c[k] || [];
c[k].push(v);
return c;
}, {})).reduce((c, v) => v.length > 1 ? c.concat(v) : c, []);
console.log(result);
关于javascript - 使用 Javascript 在对象中查找重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840157/