我一直在努力解决自己遇到的问题.我有一个包含对象的数组,像这样:
I've been trying to work out a problem I'm having. I have an array with objects in it, like this:
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 } ];我想获取其中具有重复值并基于要搜索的值的对象.即,我想获取具有重复值名称"和年龄"但重复国家/地区"的对象,所以我最终得到:
I want to get the objects that have duplicate values in them and based on what values to search for. I.e , I want to get the object that has a duplicate value "name" and "age" but nog "country" so I will end up with:
[ { 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) } })但这仅检查对象的值是否等于它们自己.
But that only checks if the values of the object is equal to them self.
有人可以帮助我吗?
推荐答案您可以使用2 reduce.第一个是对数组进行分组.第二个是仅包含具有1个以上元素的组.
You can use 2 reduce. The first one is to group the array. The second one is to include only the group with more than 1 elements.
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查找对象中的重复值
发布评论