JavaScript的 - 对象数组内重复计数 [英] JavaScript - Count duplicates within an Array of Objects
问题描述
我有对象的数组我的服务器端JS中如下:
[
{
公司:IBM
},
{
人:ACORD LOMA
},
{
公司:IBM
},
{
公司:MSFT
},
{
地方:纽约
}
]
我需要通过这个结构进行迭代,检测任何重复,然后创建一个重复的计数沿侧发现每个值。
这两个值必须匹配例如有资格作为重复公司:IBM不是公司比赛:MSFT
我如果需要改变对象的入阵的选项。我想输出是一个对象,但真的很努力得到这个工作。
编辑:这里是code我至今在这里processArray是上面列出的阵列
VAR returnObj = {}; 为(变量X = 0; X&下; processArray.length; X ++){ //检查是否已经有数组项作为回报的obj的关键
returnObj [processArray [X]] = returnObj [processArray [X]] || processArray [X]的ToString(); //设置计数场
returnObj [processArray [X]。COUNT = returnObj [processArray [X]。算|| 1; //增加计数
returnObj [processArray [X] =计数returnObj [processArray [X]数+ 1。 }
的console.log('===================='+ JSON.stringify(returnObj));
例如:
计数器= {}yourArray.forEach(函数(OBJ){
VAR键= JSON.stringify(OBJ)
计数器[关键] =(计数器[关键] || 0)+ 1
})
文件:<一href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach\">Array.forEach, <一href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify\">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.
这篇关于JavaScript的 - 对象数组内重复计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!