javascript 通过数组中每个 JSON 对象中的值从 JSON 数组中删除重复项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31962567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing duplicates from JSON array by a value in each JSON object in array
提问by SS306
If there are two JSON objects in an array with same value for a particular field, then I want to mark them as duplicate. I want to remove one of them. Similarly, when there are multiple duplicate, I only want to keep the last object(latest).If this is input:
如果数组中有两个 JSON 对象的特定字段具有相同的值,那么我想将它们标记为重复。我想删除其中之一。同样,当有多个重复时,我只想保留最后一个对象(最新)。如果这是输入:
names_array = [
{name: "a", age: 15},
{name: "a", age: 16},
{name: "a", age: 17},
{name: "b", age: 18}
{name: "b", age: 19}];
I want the output to be
我希望输出是
names_array_new =
{name: "a", age: 17},
{name: "b", age: 19}];
I have searched for this but only found how to remove duplicates when entire objects are same.
我已经搜索过这个,但只找到了如何在整个对象相同时删除重复项。
采纳答案by codebox
This should do it:
这应该这样做:
names_array = [
{name: "a", age: 15},
{name: "a", age: 16},
{name: "a", age: 17},
{name: "b", age: 18},
{name: "b", age: 19}];
function hash(o){
return o.name;
}
var hashesFound = {};
names_array.forEach(function(o){
hashesFound[hash(o)] = o;
})
var results = Object.keys(hashesFound).map(function(k){
return hashesFound[k];
})
The hashfunction decides which objects are duplicates, the hashesFoundobject stores each hash value together with the latest object that produced that hash, and the resultsarray contains the matching objects.
该hash函数决定哪些对象是重复的,该hashesFound对象将每个散列值与产生该散列的最新对象一起存储,并且该results数组包含匹配的对象。
回答by Nina Scholz
A slightly different approach:
一种稍微不同的方法:
var names_array = [
{ name: "a", age: 15 },
{ name: "a", age: 16 },
{ name: "a", age: 17 },
{ name: "b", age: 18 },
{ name: "b", age: 19 }
];
var names_array_new = names_array.reduceRight(function (r, a) {
r.some(function (b) { return a.name === b.name; }) || r.push(a);
return r;
}, []);
document.getElementById('out').innerHTML = JSON.stringify(names_array_new, 0, 4);
<pre id="out"></pre>
回答by kiran Sp
var names_array = [
{name: "a", age: 15},
{name: "a", age: 16},
{name: "a", age: 17},
{name: "b", age: 18},
{name: "b", age: 19}];
function removeDuplicate(arr, prop) {
var new_arr = [];
var lookup = {};
for (var i in arr) {
lookup[arr[i][prop]] = arr[i];
}
for (i in lookup) {
new_arr.push(lookup[i]);
}
return new_arr;}
var newArray = removeDuplicate(names_array, 'name');
console.log("Result "+newArray);
回答by B Vanitha
Array.from(new Set(brand.map(obj => JSON.stringify(obj)))).map(item => JSON.parse(item))
Array.from(new Set(brand.map(obj => JSON.stringify(obj)))).map(item => JSON.parse(item))

