Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to push an object while adding a property in one operation?

I can push an array and amend extra elements to it in one, single operation like this.

let arr = [1, 2, 3];
let col = [];
col.push(arr);
col.push([...arr, 4]);

I wonder if it’s possible to achieve something like that, a one-liner for amending and pushing, for objects.

let obj = { ... };
obj.extraInfo = "shazoo";
col.push(obj);

I haven’t found anything so I’m prepared for no-go but I’ve been wrong before.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can just do {...obj, extraInfo: "shazoo"}:

obj = { example: "demo" }
col = [];
col.push({ ...obj, extraInfo: "shazoo"});
console.log(col);

Or, if you need obj to itself be modified, you can do

 col.push(Object.assign(obj, {extraInfo: "shazoo"}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading