我找到以下answer帮助我删除包含重复项的重复对象数组。
我做了一个fork我修改的示例。
相关功能:
const uniqueArray = things.thing.filter((thing,index) => {
return index === things.thing.findIndex(obj => {
return JSON.stringify(obj) === JSON.stringify(thing);
});
});
例如我有:
[
{"place":"here","name":"stuff"},
{"place":"there","name":"morestuff"},
{"place":"there","name":"morestuff"},
{"place":"herehere","name":"stuff"}
]
它将返回:
[
{"place":"here","name":"stuff"},
{"place":"there","name":"morestuff"},
{"place":"herehere","name":"stuff"}
]
如何删除包含相同名称
的重复地点
名称?
预期输出:
[
{"place":"here","name":"stuff"},
{"place":"there","name":"morestuff"}
]
最佳答案
您可以reduce
在对象数组上。简单来说,如果累加器中已存在键值与当前对象相同的对象,则不要再次添加。
这里有一个函数,允许您指定要删除重复数据的键:
const arr = [
{"place":"here","name":"stuff"},
{"place":"there","name":"morestuff"},
{"place":"there","name":"morestuff"},
{"place":"herehere","name":"stuff"}
];
// Accepts an array and a key that should have the
// duplicates removed
function remove(arr, key) {
// Iterate over the array passing in the accumulator
// and the current element
return arr.reduce((acc, c) => {
// If there is an object in the accumulator with the
// same key value as the current element simply return the
// accumulator
if (acc.find(obj => obj[key] === c[key])) return acc;
// Otherwise add the current element to the accumulator
// and return it
return acc.concat(c);
}, []);
}
function showJSON(arr, id) {
const json = JSON.stringify(arr, null, 2);
document.querySelector(`#${id} code`).textContent = json;
}
// remove duplicate places
showJSON(remove(arr, 'place'), 'places');
// remove duplicate names
showJSON(remove(arr, 'name'), 'names');
<div id="places">
Removed duplicate places
<pre><code></code></pre>
</div>
<div id="names">
Removed duplicate names
<pre><code></code></pre>
</div>
关于javascript - 如何删除包含相同 `place` 的重复 `name` 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590897/