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

别等时光非礼了梦想. 提交于 2020-01-05 08:35:11

问题


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

回答1:


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)



回答2:


The way to do this with map would be to return a new copy. If you want to modify the original data, use a simple loop.

map example:

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


来源:https://stackoverflow.com/questions/43617467/how-do-i-replace-a-string-with-integers-in-a-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!