最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Setting all properties of an object to same value - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked May 9, 2018 at 13:17 Leo MessiLeo Messi 6,17622 gold badges77 silver badges153 bronze badges 1
  • _forOwn from lodash/underscore? try _.forOwn (missing dot). Also, what is value? – nilsK Commented May 9, 2018 at 13:21
Add a comment  | 

3 Answers 3

Reset to default 8

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);

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);

Try this simple:

for (var key in anObject) {
  anObject[key]["isGood"] = true;
}
发布评论

评论列表(0)

  1. 暂无评论