Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting all properties of an object to same value

Having an object with this structure:

anObject = {
    "a_0" : [{"isGood": true, "parameters": [{...}]}],
    "a_1" : [{"isGood": false, "parameters": [{...}]}],
    "a_2" : [{"isGood": false, "parameters": [{...}]}],
    ...
};

I want to set all isGood values to true. I've tried using _forOwn to go through the object and forEach to go through each property but it seems it's not the correct approach.

_forOwn(this.editAlertsByType, (key, value) => {
    value.forEach(element => {
        element.isSelected = false;
    });
});

The error says:

value.forEach is not a function

like image 350
Leo Messi Avatar asked Dec 11 '22 06:12

Leo Messi


2 Answers

actually you were very close, you need to use Object.keys() to get the keys of your anObject object and then loop over them and finally modify each array.

anObject = {
  "a_0": [{
    "isGood": true,
    "parameters": [{}]
  }],
  "a_1": [{
    "isGood": false,
    "parameters": [{}],
  }],
  "a_2": [{
    "isGood": false,
    "parameters": [{}],
  }],
  //...
};

Object.keys(anObject).forEach(k => {
  anObject[k] = anObject[k].map(item => {
    item.isGood = true;
    return item;
  });
})
console.log(anObject);
like image 123
Prince Hernandez Avatar answered Dec 12 '22 20:12

Prince Hernandez


Use forEach() and map() on object anObject

var anObject = {
    "a_0" : [{"isGood": true, "parameters": []}],
    "a_1" : [{"isGood": false, "parameters": []}],
    "a_2" : [{"isGood": false, "parameters": []}]
};

Object.keys(anObject).forEach((key)=>{
 anObject[key].map(obj => obj.isGood = true);
});

console.log(anObject);
like image 29
Ankit Agarwal Avatar answered Dec 12 '22 18:12

Ankit Agarwal