dzmr83
dzmr83

Reputation: 63

How to substitute all values of a certain 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 its corresponding integer in order to sort by age. Or to add a key, for example ageI with the integer value.

I could loop through the array, but, is there a better way to do that, for example with one command in jQuery?

Upvotes: 3

Views: 59

Answers (2)

akuiper
akuiper

Reputation: 214927

You can use forEach to modify the array in place:

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

Or use map to make 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) }))
);

Upvotes: 2

baao
baao

Reputation: 73221

If you just want to sort, simply sort with a callback

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

If you want the values to stay ints, use a simple loop

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

Upvotes: 2

Related Questions