Add property to all objects in array

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • 使用forEach功能:

    var array = [{ 'a': '12', 'b': '10' }, { 'a': '20', 'b': '22' }];
    
    array.forEach(function(e) { e.c = +e.b - +e.a });
       
    document.write(JSON.stringify(array));

    you can use array.map,

    and you should use Number() to convert props to numbers for adding:

    var array = [ {'a': '12', 'b':'10'}, {'a': '20', 'b':'22'} ];
    
    var r = array.map( x => {
      x.c = Number(x.b) - Number(x.a);
      return x
      })
    
    console.log(r)
    链接地址: http://www.djcxy.com/p/12054.html

    上一篇: 如何在JavaScript中迭代数组和对象

    下一篇: 将属性添加到数组中的所有对象