Skip to content Skip to sidebar Skip to footer

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',

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

Solution 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}))

Post a Comment for "How Do I Replace A String With Integers In A Multi-dimensional Array"