I want to be able to take in an object
const objectOriginal = {
nestedObject: {
someValue: 1
}
}
Create a new object from the above and change it's value to
const newObject = {
nestedObject: {
someValue: 33
}
}
I have a large object of nested objects as my original, and I want to create a new one based of this original. The problem is that I need these two objects to be different and not from the same prototype chain.
In order to solve this problem I've created a function that turns the first object to an array, filter out the object I need to change, change the values, push to an array, and then create a new object.
const originalObject = {
nested1: {
id: "nested1"
value: 1
},
nested2: {
id: "nested2"
value: 2
},
nested3: {
id: "nested3"
value: 3
}
}
const valueToChange = "nested1"
const createNewObject = (originalObject, valueToChange) => {
const originalObjectToArray = Object.values(originalObject)
const temporaryArray = originalObjectToArray.filter(object => object.id !== valueToChange)
const newNestedObject = {
id: valueToChange,
value: 33
}
temporaryArray.push(newNestedObject)
const newAndDifferentObject = {}
for (let obj of temporaryArray) {
newAndDifferentObject[obj.id] = obj
}
return newAndDifferentObject
}
This solution works, but I feel that there must be a better way to achieve this? If I want to create a new and different object, I shouldn't (at least I would hope not) have change it to an array just to change it back to an object. Any advice would be greatly appreciated.