Machtyn Machtyn - 1 year ago 51
Javascript Question

Is there a "native" Javascript function that modifies an object property

Is there a native JavaScript function (or library/module for JavaScript) that modifies a key's value and then returns the full object?

Here's what I've done:

function modifyJSON(jsob, key, val) {
var newjsob = JSON.parse(JSON.stringify(jsob));
newjsob[key] = val;
return newjsob;

(Of course, if I wanted to modify the original, I could delete
var newjsob...
and work with jsob directly.)

This works, but if this type of functionality has already been implemented somewhere, I'd prefer to use that than roll my own.

Answer Source

Your title is a little misleading. What you're doing is deep cloning an existing object and then changing a property on the new object.

If shallow cloning is enough, you could use Object.assign:

var update = {};
update[key] = val;
return Object.assign(jsob, update);

If you need deep cloning, I would check out ImmutableJS. When updating any field on an immutable data structure, a clone of the original structure with your updates applied to it is returned. It's pretty much the exact behavior you're written.