I have an array. Let's say it's:
const array = ["lvl1", "lvl2", "lvl3", "key"]
I have a value. Let's say it's:
const value = false
I have an object. Let's say it's:
const object = {
lvl1: {
dogs: "bark",
lvl2: {
cats: "meow",
lvl3: {
cows: "moo"
key: true
}
}
}
}
How do I create a function that takes in the array and value, then updates the object so that the key in the array (the last item in the array) is updated with the new value? It needs to be nested appropriately based on the first array.length - 1 strings in the array.
For example, let's called the function createObject. If I call it using the array and value already defined above as:
const newObject = createObject(array, value)
Then newObject should be equal to:
{
lvl1: {
dogs: "bark",
lvl2: {
cats: "meow",
lvl3: {
cows: "moo"
key: false
}
}
}
}
Here's another example with a different level of nesting:
const updatedObject = createObject(["lvl1", "lvl2", "cats"], "stink")
Then updatedObject should be equal to:
{
lvl1: {
dogs: "bark",
lvl2: {
cats: "stink",
lvl3: {
cows: "moo"
key: true
}
}
}
}
I've gotten this far but it's not working:
import object from "./object"
const createObject = (array, value) => {
let results = object;
for (let i = 0; i < array.length; i++) {
i === array.length - 1
? (results = results[array[i]] = {
...results[array[i]],
[array[i]]: value
})
: (results = results[array[i]] = {
...results[array[i]],
[results[array[i]]]: {}
});
}
return results;
}
I don't want to change the initial object. I want to return a new object. And I won't be adding any new key/value pairs to the object, only changing existing key/value pairs.