我在JSON数组下面有这个。在此,我想找到公用项目对象并将其添加到另一个列表中,并将其从源列表中删除。 ID为ID的项目在两个对象中很常见。此外,该列表是动态的。
[
{
"id": 1,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 2,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 3,
"item": {
"id": 2,
"name": "itemB"
}
}
]
答案 0 :(得分:0)
Array.reduce
在您的数组上,传递一个累加器。id
找到了迭代元素,如果是,则将其推入重复项。arr
。
const arr = [
{
"id": 1,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 2,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 3,
"item": {
"id": 2,
"name": "itemB"
}
}
]
const result = arr.reduce((acc, el, i) => {
if (acc.found[el.item.id]) {
acc.duplicates.push(el)
} else {
acc.source.push(el)
}
acc.found[el.item.id] = true
if (i === arr.length - 1)
delete acc.found
return acc
}, {
source: [],
duplicates: [],
found: {}
})
console.log(result.source) // source with removed duplicates
console.log(result.duplicates) // array of duplicates
答案 1 :(得分:0)
您可以结合使用reduce
和Map
来密钥数据:
const data = [ { "id": 1, "item": { "id": 1, "name": "itemA" } }, { "id": 2, "item": { "id": 1, "name": "itemA" } }, { "id": 3, "item": { "id": 2, "name": "itemB" } } ];
const [map, dupes] = data.reduce(([map, dupes], obj) =>
map.has(obj.item.id) ? [map, dupes.concat(obj)] : [map.set(obj.item.id, obj), dupes]
, [new Map, []]);
const uniques = [...map.values()];
console.log(uniques);
console.log('dupes:');
console.log(dupes);
在阅读您的评论后,您似乎想拒绝任何重复的内容,因此甚至不想保留一份原件。因此,代码可能是:
const data = [ { "id": 1, "item": { "id": 1, "name": "itemA" } }, { "id": 2, "item": { "id": 1, "name": "itemA" } }, { "id": 3, "item": { "id": 2, "name": "itemB" } } ];
const map = new Map(data.map(obj => [obj.item.id, []]));
data.forEach(obj => map.get(obj.item.id).push(obj));
const uniques = [].concat(...[...map.values()].filter(arr => arr.length === 1));
const dupes = [].concat(...[...map.values()].filter(arr => arr.length > 1));
console.log(uniques);
console.log('dupes:');
console.log(dupes);