【问题标题】:nodejs - array search and appendnodejs - 数组搜索和追加
【发布时间】:2017-09-24 22:23:11
【问题描述】:

我需要节点专家的帮助...我必须使用的版本是 0.10.x

我有一个这样的数组:

[ 
    [ 'ABC', '5' ] ,
    [ 'BCD', '1' ]
] 

我有新值要输入[ 'DDD', '3' ][ 'ABC', '4' ],我想要实现的是搜索数组中是否存在第一列 - 如果是,则总结第二列,如果不只是向数组添加值。

我希望得到的结果是:

  1. 添加[ 'DDD', '3' ] - 数组中不存在 DDD 将被添加

    [ [ 'ABC', '5' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]

  2. 添加[ 'ABC', '4' ] - ABC 存在于数组中,因此第二列将汇总为 ABC

    [ [ 'ABC', '9' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]

请帮忙

【问题讨论】:

  • 您的源数组与您想要实现的目标无关?你有更好的例子吗?
  • @Ryad - 我不是很熟练,所以我没有尝试任何东西......
  • @Alex - 也许我没有解释步骤,所以我会再次更新它
  • 我认为您需要使用对象(也称为关联数组)而不是数组来实现您想要实现的目标

标签: javascript arrays node.js


【解决方案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;
    }
  })

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多