Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change key value in the nested object array javascript

I would like to know how to change the value in a nested object array using javascript.

how to change the "load": "undefined" to "load":1 in the obj

var obj=[{
  "id": "service",
  "country": "AR",
  "load": "undefined"
},{
  "id": "fund",
  "country": "CA",
  "load": "undefined"
}]


var result = obj.forEach(e=>e.load=1);

Expected Output:
[{
  "id": "service",
  "country": "AR",
  "load": 1
},{
  "id": "fund",
  "country": "CA",
  "load": 1
}]

like image 948
Senthil Avatar asked Sep 16 '26 18:09

Senthil


2 Answers

You can do this easily with new ES2015+ syntax. Using the spread operator:

var result = obj.map(e => ({ ...e, load: 1 }));

This will keep all the other props and only change load to what you want.

Also, FYI - [].forEach() does not work this way.

like image 127
Deryck Avatar answered Sep 19 '26 06:09

Deryck


forEach does not return anything,your code is working fine so in your code the original object that is obj will be changed and if you log it show load:1. If you don't want to change original array use map which returns a new array

var obj = [{
  "id": "service",
  "country": "AR",
  "load": "undefined"
}, {
  "id": "fund",
  "country": "CA",
  "loading": "undefined"
}]


var result = obj.map(function(elem) {
  return Object.assign({}, elem, {
    // only change to 1 if value is undefined
    load: elem.load === 'undefined' ? 1 : elem.load 
  })

});
console.log(result)
like image 20
brk Avatar answered Sep 19 '26 08:09

brk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!