How to dynamically change value of a nested object

Viewed 18

Consider I have the following object:

let garages = [{
  "name": "garage LA",
  "cars": [{
      "car": "Ferrari",
      "color": "Red"
    },
    {
      "car": "Rolls Royce",
      "color": "Purple"
    },
    {
      "car": "Ferrari",
      "color": "Orange"
    }
  ]
}, {
  "name": "garage SF",
  "cars": [{
      "car": "Mercedes",
      "color": "Blue"
    },
    {
      "car": "Ferrari",
      "color": "Red"
    }
  ]
}, {
  "name": "garage NY",
  "cars": [{
    "car": "Aston Martin",
    "color": "Green"
  }]
}]

I'd like to have a function that could update a specific part of the object dynamically. For instance updateObject("Pink", [1, "cars", 1, "color"]) would basically be the same as doing garages[1]["cars"][1]["color"] = "Pink" But I do not know how many elements there will be in the array.. And I want the whole object to be returned (with that minor change).

I tried reduce but when passing the object I guess it becomes a shallow copy and nothing really happened..

Any suggestions?

0 Answers
Related