Add key value pair to all objects in array

后端 未结 10 1890
醉酒成梦
醉酒成梦 2020-12-04 10:43

I wanted to add a key:value parameter to all the objects in an array.

eg:

var arrOfObj = [{name: \'eve\'},{name:\'john\'},{name:\'jane\'}];
<         


        
10条回答
  •  [愿得一人]
    2020-12-04 11:21

    Simply use map function:

    var arrOfObj = arrOfObj.map(function(element){
       element.active = true;
       return element;
    }
    

    Map is pretty decent on compatibility: you can be reasonably safe from IE <= 9.

    However, if you are 100% sure your users will use ES6 Compatible browser, you can shorten that function with arrow functions, as @Sergey Panfilov has suggested.

提交回复
热议问题