如果某个数组中有两个JSON对象具有相同的特定字段值,那么我想将它们标记为重复。我想删除其中一个。同样,当有多个重复时,我只想保留最后一个对象(最新)。如果这是输入:
names_array = [
{name: "a", age: 15},
{name: "a", age: 16},
{name: "a", age: 17},
{name: "b", age: 18}
{name: "b", age: 19}];
我希望输出为
names_array_new =
{name: "a", age: 17},
{name: "b", age: 19}];
我搜索了这个,但只发现了当整个对象相同时如何删除重复项。
答案 0 :(得分:2)
这应该这样做:
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];
})
hash
函数决定哪些对象是重复的,hashesFound
对象将每个散列值与生成该散列的最新对象一起存储,results
数组包含匹配的对象。
答案 1 :(得分:1)
略有不同的方法:
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>
答案 2 :(得分:0)
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);
答案 3 :(得分:0)
Array.from(新Set(brand.map(obj => JSON.stringify(obj))))。map(item => JSON.parse(item))