I want to write a function that takes a keyName
, newValue
, and object
, and returns the object with the updated key/value pair. For example...
Given this data:
const data = {
token: {
id: "abcxyz",
year: "2022"
},
order_data: {
customer: "Jane",
shipping: {
country: "US",
state: "TX"
}
}
}
and a function with these arguments:
const updateObject = (keyName, newValue, object) => {
...
}
I want to be able to call:
const newObject = updateObject("customer", "Bob", data);
so that
newObject = {
token: {
id: "abcxyz",
year: "2022"
},
order_data: {
customer: "Bob",
shipping: {
country: "US",
state: "TX"
}
}
}
My current wrong attempt looks like this:
const updateObject = (keyName, newVal, object) => {
const results = {};
for (var key in object) {
if (key === keyName) {
results = {
...object,
keyName: newVal
};
} else {
results[key] = object[key];
if (typeof object[key] === "object") {
updateObject(keyName, newVal, object.key);
}
}
}
return results
};
I've been digging through posts on recursion and spread operators all day but can't quite get it right. The nested object can be any shape and depth which is throwing me off.