manuelBetancurt
manuelBetancurt

Reputation: 16128

JS map return object

I got this array,

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

What do I need to do in order to return an array mapped, that adds 10 to each launches value.

Here's my first approach:

const launchOptimistic = rockets.map(function(elem){
     return (elem.country, elem.launches+10);
});
console.log(launchOptimistic);

Upvotes: 131

Views: 371783

Answers (8)

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

If you want to alter the original objects, then a simple Array#forEach will do:

rockets.forEach(function(rocket) {
    rocket.launches += 10;
});

If you want to keep the original objects unaltered, then use Array#map and copy the objects using Object#assign:

const newRockets = rockets.map(function(rocket) {
    const newRocket = Object.assign({}, rocket);
    newRocket.launches += 10;
    return newRocket;
});

A better alternative to using Object.assign is to use the spread syntax as per Emre's answer.

Upvotes: 14

Emre
Emre

Reputation: 370

The cleanest solution is to use the spread syntax to generate the new objects:

const launchOptimistic = rockets.map(rocket => {
    return { ...rocket, launches: rocket.launches + 10 };
});

Upvotes: 13

Ricardo
Ricardo

Reputation: 821

Funny how every single solution relies on heavy funcitons and returns, except the one that uses an external accumulator, resembling more a reduce or a forEach. In any case, this subverts the original intention of the map and, in fact, of all Functional Programming: say what, not how. And yes, map is Functional Programming!

Here's a thought:

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 updated = rockets.map( rocket => ({...rocket, launches: rocket.launches + 10}) )

Please notice that:

  1. This is a true one-liner because it does not use return. (cf. Emre's answer, Stas Sorokin's answer or nir segev's answer.) The trick is the parenthesis around the result object. Without these, the syntax will "think" you're going for a code block and expect statements instead of expressions, and a return at the end.
  2. This does not change the original object (Nir Alfasi's answer) or uses global state (vera's edit)
  3. This uses destructured assignment, which is something many answers use, but funny enough, is explicitly mentioned in Stas Sorokin's answer, with the link to MDN and all. Dear Stas, foillow your own link, because your answer does NOT use destructured assignment AT ALL!
  4. This answer also fixes formatting because I was not raised by wolves. You have your spaces after commas and colons, you don't have useless semicolons because they only make sense in minified JS and webpack does that for you, and you don't have double tabs for single structure nesting (like Emre's answer), because that's just flat out fugly and almost as bad as no indentation at all.

Upvotes: 4

CRice
CRice

Reputation: 32146

You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:

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(function(elem) {
  return {
    country: elem.country,
    launches: elem.launches+10,
  } 
});

console.log(launchOptimistic);

Upvotes: 63

Nir Alfasi
Nir Alfasi

Reputation: 53525

map rockets and add 10 to its launches:

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 }
];
rockets.map((itm) => {
    itm.launches += 10
    return itm
})
console.log(rockets)

If you don't want to modify rockets you can do:

var plusTen = []
rockets.forEach((itm) => {
    plusTen.push({'country': itm.country, 'launches': itm.launches + 10})
})

Upvotes: 5

Stas Sorokin
Stas Sorokin

Reputation: 3723

Solution (One Liner) With a Fresh Example

Suppose the clients in your bank (including you, of course) got a bonus.

let finance = [
    {funds:10050, client_id: 1020},
    {funds:25000, client_id: 77},
    {funds:90000, client_id: 442}
];

finance = finance.map(({funds, client_id}) => {funds = funds + 2000; return {funds, client_id}});

↑ Test & copy as is to Chrome / Firefox / Edge DevTools console ↑

This technique called Destructuring Assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Upvotes: 4

nir segev
nir segev

Reputation: 358

Considering objects can have many properties, It would be better to spread the object's content and to reassign specific properties, to achieve code that is more succinct.

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(function(elem) {
  return {
    ...elem,
    launches: elem.launches+10,
  } 
});

console.log(launchOptimistic);

Upvotes: 4

Hemadri Dasari
Hemadri Dasari

Reputation: 33974

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);

Upvotes: 245

Related Questions