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

Loop through an array of objects using forEach

Having the following input:

const myArray = [{data: {value: 1, name: 'john', age: 22 } },{data: {value: 2, name: 'mike', age: 42 } }];

It is wanted to loop through this array in order to create a new one containing only some of the data, in this case name and age.

The result should be: [{name: 'john', age: 22 }, {name: 'mike', age: 42 }]

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

I’ve tried to use forEach:

const result = myArray.forEach(el => ({el.data.name, el.data.age}));

What is wrong with this solution?

>Solution :

As Array#forEach() method does not return a value, we do not assign it to a variable but rather use it as we would a loop:

const myArray = [{data: {value: 1, name: 'john', age: 22 } },{data: {value: 2, name: 'mike', age: 42 } }];

const result = [];
myArray.forEach( ({data: {name,age}}) => result.push( {name,age} ) );

console.log( result );

OR:

const myArray = [{data: {value: 1, name: 'john', age: 22 } },{data: {value: 2, name: 'mike', age: 42 } }];

const result = [];
myArray.forEach( ({data: {value, ...desired}}) => result.push( desired ) );

console.log( result );
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