Home > Blockchain >  Loop through an array of objects using forEach
Loop through an array of objects using forEach

Time:12-03

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?

CodePudding user response:

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 );
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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 );
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related