如何在多维数组中将字符串替换为整数 [英] How do I replace a string with integers in a multi-dimensional array

查看:106
本文介绍了如何在多维数组中将字符串替换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个对象数组:

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

我正在尝试使用map,filter,reduce转换上述数组.即使可以轻松隔离特定的数据集,也无法更改原始数组.

I'm trying to transform the above array using map, filter, an reduce. I'm having trouble altering the original array even though I can easily isolate a specific data set.

例如:

我正在尝试将每个人拥有的汽车数量更改为数字而不是字符串,所以...

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?

预期结果:

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

推荐答案

您可以只使用forEach循环并将字符串更改为数字. map()方法创建一个新数组.

You can just use forEach loop and change string to number. map() method creates a new array.

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)

这篇关于如何在多维数组中将字符串替换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆