How to replace all values ​​of a specific key in an array of JSON objects

I have an array of JSON object, for example people

with data, for example:

[
  {
    name : 'John',
    age : '7'
  },
  {
    name : 'Mary',
    age : '70'
  },
  {
    name : 'Joe',
    age : '40'
  },
  {
    name : 'Jenny',
    age : '4'
  }
]

      

I want to substitute all string values ​​in age

for their respective integer in order to sort by age

. Or add a key, for example ageI

with an integer value.

I could walk through the array, but is there a better way to do this, for example with a single command in jQuery?

+3


source to share


2 answers


You can use forEach

to change array

:

var array = [
  {
    name : 'John',
    age : '7'
  },
  {
    name : 'Mary',
    age : '70'
  },
  {
    name : 'Joe',
    age : '40'
  },
  {
    name : 'Jenny',
    age : '4'
  }
]


array.forEach(obj => { obj.age = Number(obj.age) });

console.log(array);
      

Run codeHide result




Or use map

to create a new array:

var array = [
      {
        name : 'John',
        age : '7'
      },
      {
        name : 'Mary',
        age : '70'
      },
      {
        name : 'Joe',
        age : '40'
      },
      {
        name : 'Jenny',
        age : '4'
      }
    ]
    
console.log(
  array.map(obj => ({ name: obj.name, age: Number(obj.age) }))
);
      

Run codeHide result


+2


source


If you just want to sort, just do the sort with a callback

arr.sort((a,b) => parseInt(a.age, 10) - parseInt(b.age, 10));

      



If you want the values ​​to remain ints use a simple loop

arr.forEach(e => e.age = parseInt(e.age, 10));

      

+2


source







All Articles