简体   繁体   中英

How to change property values in an array Object?

I'm trying to change the values of each property in an array using a forEach function but not having any luck.

Here's my array:

  this.panels = [
  { isRandomPanel  : false },
  { isMyPanel  : false },
  { isFavorite      : false },
  { isEatable : false }
  ]

I'm trying to update the value of each property to true so finally I can get this:

 isRandomPanel = true
 isMyPanel  = true
 isFavorite = true
 isEatable = true

I'm trying to use the forEach function but I'm stuck:

   this.panels.forEach(panel => panel.isRandomPanel = true);

Does anyone know how to make this happen using pure Javascript, TypeScript or ES6?

If those are the only keys on the objects, you can iterate over Object.keys(panel) and set each panel[key] = true , like so:

 var panels = [ { isRandomPanel : false }, { isMyPanel : false }, { isFavorite : false }, { isEatable : false } ]; // set all panel flags to true panels.forEach(function (panel) { Object.keys(panel).forEach(function (key) { panel[key] = true; }); }); console.log(panels);

Or, with shortened ES6 Syntax:

panels.forEach(panel => Object.keys(panel).forEach(key => panel[key] = true));

You need to itreate over the array, get each key from the object and set the value of that key to true. You can use Object.keys or for in loop to get the keys:

this.panels.forEach(panel => {
  for(const key of Object.keys(panel))
    panel[key] = true
})

OR

this.panels.forEach(panel => {
  for(const key in panel)
    panel[key] = true
})

当您使用 ES 6 时,以下将起作用

panels.forEach(panel => Object.keys(panel).forEach(key => panel[key] = true));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM