How can you update an entire object, say:
var x = {a:1}
function modify(obj) {
obj = {b:2}
}
modify(x)
console.log(x) // {a:1}
But maintain the reference? I want the object to be modified outside the function.
My specific case is using lodash.pick
inside my function:
if (whitelist) {
obj = _.pick(obj, whitelist)
}
I can't seem to find a pick
function that modifies the object. Is there a way to do this or do I need to start returning copies of the object?
delete
everything from the old object, and then add new properties, key-by-key:
function modify(obj, newObj) {
Object.keys(obj).forEach(function(key) {
delete obj[key];
});
Object.keys(newObj).forEach(function(key) {
obj[key] = newObj[key];
});
}
var x = {a:1}
modify(x, {b:42})
document.write(JSON.stringify(x));
If you're wondering whether it's a good idea in general, the answer is no. Construct a new object, return it from the function and assign - this is a much preferred way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With