2017-05-10 62 views
1

數組名稱我有一個數組一些對象:映射對象及其與環

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

我試圖用一個循環增加值,使我有這樣的事情:

var myArray = [{ 
    'id': 'first', 
    'value': 'firstValue', 
    'inc1' : 1 
}, { 
    'id': 'second', 
    'value': 'secondValue' 
    'inc2' : 2 
}, { 
    'id': 'third', 
    'value': 'thirdValue' 
    'inc3' : 3 
}]; 

我知道,與映射

myArray.forEach(function(o, i) { 
    o.inc = i + 1;     
}); 

我能得到的結果增加,但如何讓名INC1,INC2,INC3 ...?

+2

只是好奇:你爲什麼要到號碼添加到屬性名稱? – Andreas

回答

4

你可以用括號標記爲財產property accessor,像

object.property // dot notation 
object['property'] // bracket notation 

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

 
myArray.forEach(function (o, i) { 
 
    o['inc' + (i + 1)] = i + 1; 
 
    //^^^^^^^^^^^^^^^^ use brackets and property as string 
 
}); 
 

 
console.log(myArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

這很好用,謝謝! – Rockasaurus