Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS map return object

I got this array,

var rockets = [     { country:'Russia', launches:32 },     { country:'US', launches:23 },     { country:'China', launches:16 },     { country:'Europe(ESA)', launches:7 },     { country:'India', launches:4 },     { country:'Japan', launches:3 } ]; 

What do I need to do to return an array mapped, that adds 10 to each

launches

value, here my first approach,

var launchOptimistic = rockets.map(function(elem){   // return  elem.launches+10;      return (elem.country, elem.launches+10);   }); console.log(launchOptimistic); 
like image 759
manuelBetancurt Avatar asked Dec 16 '17 02:12

manuelBetancurt


People also ask

Can maps return objects?

. map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.

What does map return in JavaScript?

Return Value: It returns a new array and elements of arrays are result of callback function. Below examples illustrate the use of array map() method in JavaScript: Example 1: This example use array map() method and return the square of array element.

Does .map always return an array?

map() does not change the original array. It will always return a new array.


1 Answers

Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended

const rockets = [      { country:'Russia', launches:32 },      { country:'US', launches:23 },      { country:'China', launches:16 },      { country:'Europe(ESA)', launches:7 },      { country:'India', launches:4 },      { country:'Japan', launches:3 }  ];    const launchOptimistic = rockets.map(elem => (    {      country: elem.country,      launches: elem.launches+10    }   ));    console.log(launchOptimistic);
like image 136
Hemadri Dasari Avatar answered Oct 23 '22 22:10

Hemadri Dasari