使用循环映射数组中的对象

时间:2017-04-07 20:32:58

标签: javascript arrays mapping

我有一个带有一些对象的数组:

module.exports = function(db, maybeOtherSharedResources) {
  // existing code from route.js
}

我正在尝试使用'for'循环添加值,以便我有这样的东西:

var myArray = [{
    'id': 'first',
    'value': 'firstValue'
}, {
    'id': 'second',
    'value': 'secondValue'
}, {
    'id': 'third',
    'value': 'thirdValue'
}, etc.];

我试图用映射

来做
var myArray = [{
    'id': 'first',
    'value': 'firstValue',
    'inc' : 1
}, {
    'id': 'second',
    'value': 'secondValue'
    'inc' : 2
}, {
    'id': 'third',
    'value': 'thirdValue'
    'inc' : 3
}, etc.];

但是我在数组中的所有'inc'值都是相同的(全部等于49,少于'myArray.length')。我错过了什么?

3 个答案:

答案 0 :(得分:2)

您不需要外部for循环,只需使用index参数map耗材:

var withIncAdded = myArray.map(function(obj, index) {
    obj.inc = index + 1;
    return obj;
});

Array.map documentation

答案 1 :(得分:2)

您可以直接向对象添加属性,使用map会导致错误,因为它未在对象上定义。试试这个:

myArray.forEach(function(o, i) { // for each object o in the array
  o.inc = i + 1;                 // add a property inc equal to it's index + 1
});

或者在最近的ECMAScripts中:

myArray.forEach((o, i) => o.inc = i + 1);

答案 2 :(得分:2)

Array#map本身就是一个循环所以将它放在另一个for循环中并不是一个明智的想法。

无论如何我建议你使用Array#forEach。它的工作速度比Array#map快,因为它不会返回新的数组。

var myArray = [{'id':'first','value':'firstValue'},{'id':'second','value':'secondValue'},{'id':'third','value':'thirdValue'}]
    myArray.forEach((v,i) => v.inc = i+1);

    console.log(myArray);