0

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Soerman
  • 184
  • 8
  • This seems rather redundant. For the logic to work you would need to have advanced knowledge of the structure of the object in order to pass the array `[1, "cars", 1, "color"]` to the second argument. Therefore your code is not any more convenient than just accessing and updating the object directly. – Rory McCrossan Sep 19 '22 at 15:37
  • you could use recursion: `const updateObjectGen = (obj, val, path) => {path.length > 1 ? updateObjectGen(obj[path.shift()], val, path) : obj[path[0]] = val};` with `const updateObject = updateObject(garages)` – kikon Sep 19 '22 at 15:49
  • Rory, I will be very aware of the structure. But I cannot update the object like so, since the variable is a useState-variable in react. – Soerman Sep 20 '22 at 17:18
  • Kikon, I've tried something similar but don't know how to return the full object – Soerman Sep 20 '22 at 17:18

0 Answers0