我需要节点专家的帮助...我必须使用的版本是0.10.x
我有这样的数组:
[
[ 'ABC', '5' ] ,
[ 'BCD', '1' ]
]
我有新的值进入[ 'DDD', '3' ]
和[ 'ABC', '4' ]
,我想实现的是搜索是否存在数组中的第一列 - 如果是,如果是的,请加上第二列,如果不只是在数组中添加值。
结果我希望有:
添加
[ 'DDD', '3' ]
-DDD在数组中不存在,将添加[ [ 'ABC', '5' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]
添加
求和第二列[ 'ABC', '4' ]
-ABC存在于数组中,因此将对ABC[ [ 'ABC', '9' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]
请帮助
您的对象初始值:
var myObj = [{'ABC': '5'}, {'BCD': '1'}]
现在,如果DDD
不存在,只需添加:
var DDD = "3"
var DDDExists = false;
myObj.forEach(function(){
if(this.DDD.length > 0){
// If it exists, break the loop
DDDExists = true;
break;
}
})
// If DDD doesn't exists, add it
if(DDDExists === false){
// Add DDD object to array
myObj.push({'DDD': 3});
}
现在,如果存在ABC
,请将ABC
总和到所有可用值:
// Check if ABC exists
var ABCExsits = false;
myObj.forEach(function(){
if(this.ABC.length > 0){
// If ABC exits, break the loop
ABCExists = true;
break;
}
})
if(ABCExists === true){
// Sum all the values
var totalSum = 0;
myObj.forEach(function(){
// Since we don't know the name property of the obj, we need to do a for loop
for(var prop in this){
totalSum = totalSum + this[prop];
}
})
// Now add `totalSum` to ABC
myObj.foreach(function(){
if(this.ABC.length > 0){
this.ABC = totalSum;
break;
}
})
}