简体   繁体   中英

Loop through an array of objects using forEach [closed]

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 }]

I've tried to use forEach:

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

What is wrong with this 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 );

Using map and destructuring in one line. Since you need new array with same amount of items, map will be handy.

 const myArray = [ { data: { value: 1, name: "john", age: 22 } }, { data: { value: 2, name: "mike", age: 42 } }, ]; const result = myArray.map(({ data: { name, age } }) => ({ name, age })); console.log(result);

You cannot modify the array with foreach, since it doesn't return anything. You have to use map for that.

Also, you don't need to specify each element, you can just set it to el.data

 var myArray = [{data: {value: 1, name: 'john', age: 22 } },{data: {value: 2, name: 'mike', age: 42 } }]; const result = myArray.map(el => el.data); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM