计算对象数组中的重复项 [英] Count duplicates within an Array of Objects
问题描述
我的服务器端 JS 中有一个对象数组,如下所示:
<预><代码>[{公司":IBM"},{人":ACORD LOMA"},{公司":IBM"},{公司":MSFT"},{地点":纽约"}]我需要遍历这个结构,检测任何重复项,然后在每个值旁边创建一个重复项的计数.
两个值必须匹配才能被视为重复,例如公司":IBM"与公司":MSFT"不匹配.
如果需要,我可以选择更改入站对象数组.我希望输出是一个对象,但我真的很难让它工作.
这是我到目前为止的代码,其中 processArray 是上面列出的数组.
var returnObj = {};for(var x=0; x
例如:
计数器 = {}yourArray.forEach(function(obj) {var key = JSON.stringify(obj)计数器[密钥] = (计数器[密钥] || 0) + 1})
文档:Array.forEach、JSON.stringify.
I have an array of objects as follows within my server side JS:
[
{
"Company": "IBM"
},
{
"Person": "ACORD LOMA"
},
{
"Company": "IBM"
},
{
"Company": "MSFT"
},
{
"Place": "New York"
}
]
I need to iterate through this structure, detect any duplicates and then create a count of a duplicate is found along side each value.
Both of the values must match to qualify as a duplicate e.g. "Company": "IBM" is not a match for "Company": "MSFT".
I have the options of changing the inbound array of objects if needed. I would like the output to be an object, but am really struggling to get this to work.
EDIT: Here is the code I have so far where processArray is the array as listed above.
var returnObj = {};
for(var x=0; x < processArray.length; x++){
//Check if we already have the array item as a key in the return obj
returnObj[processArray[x]] = returnObj[processArray[x]] || processArray[x].toString();
// Setup the count field
returnObj[processArray[x]].count = returnObj[processArray[x]].count || 1;
// Increment the count
returnObj[processArray[x]].count = returnObj[processArray[x]].count + 1;
}
console.log('====================' + JSON.stringify(returnObj));
For example:
counter = {}
yourArray.forEach(function(obj) {
var key = JSON.stringify(obj)
counter[key] = (counter[key] || 0) + 1
})
Docs: Array.forEach, JSON.stringify.
这篇关于计算对象数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!