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 store an object inside an array?

I have two arrays and I want to store them in one array and create them as an object.

const name = ["Amy", "Robert", "Sofie"];
const age = ["21", "28", "25"];

The output I want is:

const person =[{name: 'Amy', age: '21'}, {name: 'Robert', age: '28'}, {name: 'Sofie', age: '25'}];

Is there a way that I can loop it to make it like this because my array is very long would be bothersome to manually type it. Thanks.

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 could use Array.map like:

const names = ["Amy", "Robert", "Sofie"];
const ages = ["21", "28", "25"];

const persons = names.map((name, i) => ({name, age: ages[i]}));

console.log(persons)

Take in consideration that the arrays length have to be equal.
And use plural when naming Arrays.

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