JS地图返回对象

时间:2017-12-16 02:03:43

标签: javascript dictionary

我有这个数组,

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

返回映射的数组需要做什么,每个

增加10个
  

发射

值,这是我的第一个方法,

var launchOptimistic = rockets.map(function(elem){
  // return  elem.launches+10;
     return (elem.country, elem.launches+10);


});
console.log(launchOptimistic);

4 个答案:

答案 0 :(得分:23)

你已经非常接近了,你只需要返回你想要的新对象。在这种情况下,相同的一个除了启动值增加10:



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

var launchOptimistic = rockets.map(function(elem) {
  return {
    country: elem.country,
    launches: elem.launches+10,
  } 
});

console.log(launchOptimistic);




答案 1 :(得分:9)

使用.map而不用简单的方式返回。还要开始使用let和const而不是var,因为更推荐使用let和const

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

答案 2 :(得分:4)

map火箭并在其发布时添加10个:



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




如果您不想修改rockets,可以执行以下操作:

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

答案 3 :(得分:3)

如果你想改变原始对象,那么一个简单的Array#forEach就可以了:

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

如果您希望保持原始对象不变,请使用Array#map并使用Object#assign复制对象:

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