如何在JavaScript中的JSON数组中获取重复的对象 [英] How to get repeated objects in json array in javascript
本文介绍了如何在JavaScript中的JSON数组中获取重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的JSON数组:
I have a JSON array like this :
var data = [
{title: "HH02"},
{title: "HH03"},
{title: "HH04"},
{title: "HH02"},
{title: "HH07"},
{title: "HH08"},
{title: "HH08"},
{title: "HH10"},
{title: "HH02"},
{title: "HH11"}
]
首先,我想像这样在JSON数组中获取重复的对象:
First I would like to get repeated objects in JSON array like this:
var output = [
{title: "HH02" },
{title: "HH08" },
]
然后我想获取所有重复的对象以及它们在这样的另一个JSON数组中重复多少次
Then I would like to get all repeated objects and how many times they are repeated in another JSON array like this
var output = [
{title: "HH02" , repeat: 3},
{title: "HH08" , repeat: 2},
]
我尝试这样做,但是效果不佳:
I tried doing this, but it didn't work well:
data.map(v => v.title).sort().sort((a, b) => {
if (a === b) output.push(a);
})
推荐答案
您可以使用减少,过滤和映射
- 首先按
title
将所有值分组,然后在其中重复 - 过滤
标题
,该标题出现一次或少于一次,然后出现一次(排除它们) - 映射它们以获得所需的输出
- Group all the values by
title
first, count there repetition - Filter the
titles
which appears once or less then once ( exclude them ) - map them to get desired output
var data = [{title: "HH02"},{title: "HH03"},{title: "HH04"},{title: "HH02"},{title: "HH07"},{title: "HH08"},{title: "HH08"},{title: "HH10"},{title: "HH02"},{title: "HH11"}]
let final = [...data.reduce((op, inp) => {
let title = inp.title
op.set(title, (op.get(title) || 0) + 1)
return op
}, new Map()).entries()].filter(([_,repeat]) => repeat > 1).map(([title, repeat]) => ({
title,
repeat
}))
console.log(final)
这篇关于如何在JavaScript中的JSON数组中获取重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文