nodejs - 数组搜索和追加
Posted
技术标签:
【中文标题】nodejs - 数组搜索和追加【英文标题】:nodejs - array search and append 【发布时间】:2017-09-24 22:23:11 【问题描述】:我需要节点专家的帮助...我必须使用的版本是 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' ]
]
请帮忙
【问题讨论】:
您的源数组与您想要实现的目标无关?你有更好的例子吗? @Ryad - 我不是很熟练,所以我没有尝试任何东西...... @Alex - 也许我没有解释步骤,所以我会再次更新它 我认为您需要使用对象(也称为关联数组)而不是数组来实现您想要实现的目标 【参考方案1】:你的对象初始值:
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;
)
【讨论】:
以上是关于nodejs - 数组搜索和追加的主要内容,如果未能解决你的问题,请参考以下文章