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 add object within array in javascript?

I have a array object now I want to add another object inside existing array object as given below:-

Output should be like this:- [{​a:1,b:2,c:3,d:4}​]

let a =[{a:1,b:2,c:3}];
let d={d:4}

console.log([...a,d]);

Thanks for your support!

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 :

To get the shown output (single object in an array), you can spread (add) d into a[0]

let a = [{a:1,b:2,c:3}];
let d={d:4}
a[0] = { ...a[0], ...d }
console.log(a);

But if you don’t need a dynamic solution, I’d recommend dales way:

a[0]['d'] = 4
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