简体   繁体   English

通过数组中每个JSON对象中的值从JSON数组中删除重复项

[英]Removing duplicates from JSON array by a value in each JSON object in array

If there are two JSON objects in an array with same value for a particular field, then I want to mark them as duplicate . 如果在一个数组中有两个JSON对象,对于特定的字段具有相同的值,那么我想将它们标记为重复 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: 同样,当有多个重复项时,我只想保留最后一个对象(最新)。

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. 我已经进行了搜索,但是只发现了在整个对象相同时如何删除重复项。

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 hash function decides which objects are duplicates, the hashesFound object stores each hash value together with the latest object that produced that hash, and the results array contains the matching objects. hash函数决定哪些对象是重复的, hashesFound对象将每个哈希值与产生该哈希值的最新对象存储在一起, results数组包含匹配的对象。

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> 

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);

Array.from(new Set(brand.map(obj => JSON.stringify(obj))))。map(item => JSON.parse(item))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM