How to change data in a nested JSON by javascript lodash

for example, i have a JSON file like this

{
  "employees": [
    { "name": "Ram", "email": "ram@gmail.com", "age": 23 },
    { "name": "Shyam", "email": "shyam23@gmail.com", "age": 28 },
    { "name": "John", "email": "john@gmail.com", "age": 33 },
    { "name": "Bob", "email": "bob32@gmail.com", "age": 33 }
  ]
}

Now i want to create a new array that same as this, but modded specific value, like if age is 33 then change to 1, like

{
  "employees": [
    { "name": "Ram", "email": "ram@gmail.com", "age": 23 },
    { "name": "Shyam", "email": "shyam23@gmail.com", "age": 28 },
    { "name": "John", "email": "john@gmail.com", "age": 1 },
    { "name": "Bob", "email": "bob32@gmail.com", "age": 1 }
  ]
}

How can i do this with lodash or javascript array ? Thank you guy a lots

Answer

In order to create a new array you need to take care not to modify the existing elements of the array. You can do this in a number of ways, however because your data is multiple levels, using functions like Array.map() or the Spread operator (...) can be problematic. You need to copy the data first. One way is using JSON.stringify() and JSON.parse() to create the copy, then modify it using an Array maniulation method (.map(), .reduce(), .forEach(), etc) to modify the data.

var data = {
  employees: [
    { name: "Ram", email: "ram@gmail.com", age: 23 },
    { name: "Shyam", email: "shyam23@gmail.com", age: 28 },
    { name: "John", email: "john@gmail.com", age: 33 },
    { name: "Bob", email: "bob32@gmail.com", age: 33 }
  ]
}

var copy = JSON.parse(JSON.stringify(data))
copy.employees.map( elem => { elem.age = elem.age==33?1:elem.age; return elem } )
console.log(copy)