所以我有一个对象数组:
var arr = [
{name: 'John', cars: '2', railcard: 'yes', preferences: ['taxi', 'tram', 'walking']},
{name: 'Mary', cars: '0', railcard: 'no', preferences: ['cyling', 'walking', 'taxi']},
{name: 'Elon', cars: '100000', railcard: 'no', preferences: ['Falcon 9', 'self-driving', 'Hyper-loop']}
];我正在尝试使用map,filter,来转换上面的数组。尽管我可以很容易地隔离特定的数据集,但我在更改原始数组时遇到了困难。
例如:
我想把每个人拥有的汽车数量改为一个数字而不是一个字符串,所以.
var cars = arr.map(function(arr) {return arr.cars});
var carsToNumber = cars.map(function(x) {return parseInt(x)});现在如何替换数组中的原始字符串值?
预期结果:
var arr = [
{name: 'John', cars: 2, railcard: 'yes', preferences: ['taxi', 'tram', 'walking']},
{name: 'Mary', cars: 0, railcard: 'no', preferences: ['cyling', 'walking', 'taxi']},
{name: 'Elon', cars: 100000, railcard: 'no', preferences: ['Falcon 9', 'self-driving', 'Hyper-loop']}
];发布于 2017-04-25 17:42:33
您只需使用forEach循环并将字符串更改为number即可。map()方法创建一个新数组。
var arr = [
{name: 'John', cars: '2', railcard: 'yes', preferences: ['taxi', 'tram', 'walking']},
{name: 'Mary', cars: '0', railcard: 'no', preferences: ['cyling', 'walking', 'taxi']},
{name: 'Elon', cars: '100000', railcard: 'no', preferences: ['Falcon 9', 'self-driving', 'Hyper-loop']}
];
arr.forEach(e => e.cars = +e.cars);
console.log(arr)
发布于 2017-04-25 17:46:08
使用map进行此操作的方法是返回一个新副本。如果要修改原始数据,请使用简单的循环。
map示例:
const updatedArr = arr.map(item => Object.assign({}, item, {cars: +item.cars}))https://stackoverflow.com/questions/43617467
复制相似问题