Home > OS >  how do I replace values of specific keys in an array of objects? javascript
how do I replace values of specific keys in an array of objects? javascript

Time:11-11

I have an array of objects where I need to modify and replace values of specific keys:

arr = [ {key: 'a', value: 1}, {key: 'b', value: 2}, {key: 'c', value: 3}, {key: 'd', value: 4}, {key: 'e', value: 5}]

furthest I could figure was to filter arr.filter(i => i.key.includes('b','c','d')).map(i => i.value) but this would stop only on the first included filter and hold only one value (2). Id thought it would hold objects of keys b c d which values id then modify.

const arr = [{
  key: 'a',
  value: 1
}, {
  key: 'b',
  value: 2
}, {
  key: 'c',
  value: 3
}, {
  key: 'd',
  value: 4
}, {
  key: 'e',
  value: 5
}]

console.log(arr.filter(i => i.key.includes('b', 'c', 'd')).map(i => i.value))

CodePudding user response:

Just iterate array and check if key of item matches desired keys and if so assign new value. Because arr is an array of objects and objects are stored by reference you can alter the object directly without creating a new one.

const keys = ["a", "b", "c"];
const newValue = 1;

arr.forEach((item) => {
  if (keys.includes(item.key)) {
     item.value = newValue;
  }
})
  • Related