Similar to what lenses can do in functional languages, is there a way in JavaScript to return a new object identical to the original, but with some elements having been modified?
var myObject = {
label: 'Table',
options: ['legs'],
params: {
colour: 'red',
feet: {
colour: 'white',
shape: 'round'
}
}
}
function newObject(obj) {
// sought-after syntax here
return obj({ params.colour = 'green', params.feet.shape = 'square' })
}
console.log(newObject(myObject))
{
label: 'Table',
options: ['legs'],
params: {
colour: 'green',
feet: {
colour: 'white',
shape: 'square'
}
}
}
Note: newObject()
returns a new object, without having affected the original in any shape or form.