我的服务器端 JS 中有如下对象数组:
[
{
"Company": "IBM"
},
{
"Person": "ACORD LOMA"
},
{
"Company": "IBM"
},
{
"Company": "MSFT"
},
{
"Place": "New York"
}
]
我需要遍历此结构,检测任何重复项,然后在每个值旁边创建一个重复项计数。
两个值都必须匹配才有资格作为重复项,例如“公司”:“IBM”不匹配“公司”:“MSFT”。
如果需要,我可以选择更改入站对象数组。我希望输出是一个对象,但我真的很难让它工作。
编辑:这是我到目前为止的代码,其中 processArray 是上面列出的数组。
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));
原文由 Ben 发布,翻译遵循 CC BY-SA 4.0 许可协议
例如:
文档: Array.forEach , JSON.stringify 。