TheRealFakeNews
TheRealFakeNews

Reputation: 8183

How to create a clone of an object with some fields changed?

I have an object

const anObj = {a: 1, b: 2, c: 3};

I want to create a copy of it, but with some fields changed. I want to do this in one line. Currently, I have:

const anotherObj = Object.assign({}, anObj);
anotherObj.a = anotherObj.a * 100;

How can I combine these two in to one step so that anotherObj is {a: 100, b: 2, c: 3}?

Upvotes: 2

Views: 143

Answers (1)

NineBerry
NineBerry

Reputation: 28549

const anotherObj = Object.assign({}, anObj, {a : anObj.a * 100});

Upvotes: 3

Related Questions