Ad

How Can I Modify Date Inside Json Object?

- 1 answer

How can i modify value inside object?

For example from this object that contain total of days

const data = {
"A": [{
         id: 1,
         day: 12
     },{
         id: 2,
         day: 14
     }]
 }

And add 1 day to day object to become something like this

const data = {
"A": [{
         id: 1,
         day: 13
     },{
         id: 2,
         day: 15
     }]
 } 
Ad

Answer

data.A.forEach(item => item.day++);

Working snippet:

const data = { A: [{ id: 1, day: 12 }, { id: 2, day: 14 }] };

data.A.forEach(item => item.day++);

console.log(data)

Or, if you don't want to mutate data:

const newData = { A: data.A.map(item => ({id: item.id, day: item.day + 1})) }

Working snippet:

const data = { A: [{ id: 1, day: 12 }, { id: 2, day: 14 }] };

const newData = {
  A: data.A.map(item => ({ id: item.id, day: item.day + 1 }))
}

console.log(newData)

Ad
source: stackoverflow.com
Ad