admin管理员组文章数量:1131627
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);
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);
Share
Improve this question
edited Sep 18, 2023 at 18:51
Jack_Hu
1,35911 silver badges20 bronze badges
asked Dec 16, 2017 at 2:03
manuelBetancurtmanuelBetancurt
16.1k33 gold badges127 silver badges226 bronze badges
2
- Do you want to alter the original objects? Or do you want to create new objects (copies)? – ibrahim mahrir Commented Dec 16, 2017 at 2:07
- return array similar can be new – manuelBetancurt Commented Dec 16, 2017 at 2:08
8 Answers
Reset to default 245Use .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);
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);
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.
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 };
});
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})
})
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);
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.
Funny how every single solution relies on heavy funcitons and return
s, 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:
- 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 areturn
at the end. - This does not change the original object (Nir Alfasi's answer) or uses global state (vera's edit)
- 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!
- 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.
本文标签: javascriptJS map return objectStack Overflow
版权声明:本文标题:javascript - JS map return object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736778576a1952472.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论