Add key value pair to all objects in array

后端 未结 10 1853
醉酒成梦
醉酒成梦 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:17

    Looping through the array and inserting a key, value pair is about your best solution. You could use the 'map' function but it is just a matter of preference.

    var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
    arrOfObj.map(function (obj) { 
       obj.isActive = true;
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 11:22

    Simply you can add that way. see below the console image

    0 讨论(0)
  • 2020-12-04 11:24

    You may also try this:

    arrOfObj.forEach(function(item){item.isActive = true;});
    
    console.log(arrOfObj);
    
    0 讨论(0)
  • 2020-12-04 11:25

    @Redu's solution is a good solution

    arrOfObj.map(o => o.isActive = true;) but Array.map still counts as looping through all items.

    if you absolutely don't want to have any looping here's a dirty hack :

    Object.defineProperty(Object.prototype, "isActive",{
      value: true,
      writable: true,
      configurable: true,
      enumerable: true
    });
    

    my advice is not to use it carefully though, it will patch absolutely all javascript Objects (Date, Array, Number, String or any other that inherit Object ) which is really bad practice...

    0 讨论(0)
  • 2020-12-04 11:27

    You can do this with map()

    var arrOfObj = [{
      name: 'eve'
    }, {
      name: 'john'
    }, {
      name: 'jane'
    }];
    
    var result = arrOfObj.map(function(o) {
      o.isActive = true;
      return o;
    })
    
    console.log(result)

    If you want to keep original array you can clone objects with Object.assign()

    var arrOfObj = [{
      name: 'eve'
    }, {
      name: 'john'
    }, {
      name: 'jane'
    }];
    
    var result = arrOfObj.map(function(el) {
      var o = Object.assign({}, el);
      o.isActive = true;
      return o;
    })
    
    console.log(arrOfObj);
    console.log(result);

    0 讨论(0)
提交回复
热议问题