0

I have an Array of Objects

var array = [ {type: 'news', id: 1}, {type: 'contacts', id: 7}, {type: 'messages', id: 11} ]

I need a decision that I can add a property and value to an Object. Which to define which object to add a property to, I have a type

Something like

function(arr = array, type = 'news', property = 'visibility ', value = 'yes') {

    var obj = arr.find(item => item.type === type)

    /* magic */


    return result


}


result = [ {type: 'news', id: 1, visibility: 'yes'}, {type: 'contacts', id: 7}, {type: 'messages', id: 11} ]
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Possible duplicate of [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Heretic Monkey Jun 11 '18 at 12:26

2 Answers2

0

Simple answer is (if you are OK with mutating the existing object):

obj[property] = value

If mutations are not allowed then:

function(arr = array, type = 'news', property = 'visibility ', value = 'yes') {
  return arr.map((item) => {
    if(item.type === type) {
      return {...item, [property]: value}
    }
    return item
  })
}
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
0

Assuming that array could contain more than one object === type, you can use the function forEach and Object.assing to set new properties for every matched object.

This approach mutates the objects from the original array.

function findNSet(arr, type, property, value) {
  arr.forEach(o => {
    if (o.type === type) Object.assign(o, {[property]: value});
  });
}

let array = [{type: 'news',  id: 1}, {  type: 'contacts',  id: 7}, {  type: 'messages',  id: 11}];

findNSet(array, 'news', 'visibility', 'yes');
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75