简体   繁体   English

如何在多维数组中用整数替换字符串

[英]How do I replace a string with integers in a multi-dimensional array

So I have an array of objects : 所以我有一个对象数组:

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

I'm trying to transform the above array using map, filter, an reduce. 我正在尝试使用map,filter,reduce转换上述数组。 I'm having trouble altering the original array even though I can easily isolate a specific data set. 即使可以轻松隔离特定的数据集,也无法更改原始数组。

For example: 例如:

I'm trying to change the amount of cars owned by each person to be a number and not a string so... 我正在尝试将每个人拥有的汽车数量更改为数字而不是字符串,所以...

var cars = arr.map(function(arr) {return arr.cars});
var carsToNumber = cars.map(function(x) {return parseInt(x)});

How do I now replace the original string values in the array? 现在如何替换数组中的原始字符串值?

Expected result: 预期结果:

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

You can just use forEach loop and change string to number. 您可以只使用forEach循环并将字符串更改为数字。 map() method creates a new array. 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) 

The way to do this with map would be to return a new copy. 使用map进行此操作的方法是返回新副本。 If you want to modify the original data, use a simple loop. 如果要修改原始数据,请使用一个简单的循环。

map example: map示例:

const updatedArr = arr.map(item => Object.assign({}, item, {cars: +item.cars}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM