Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map json object to array

I have json:

{
  "userList":
  [{
    "name": "Bob",
    "age": 28
  },{
    "name": "Tom",
    "age": 45
  },{
    "name": "Alice",
    "age": 32
  }]
}

I want to cut only age and put them to array like : public mainChartData1: Array = [28, 45, 32];

I have started to do that by next code:

  const arr = this.users.map(obj => {

    var localObj = [];
      localObj[obj] = obj.age;
      return localObj;

    });

But it doesn't work.

like image 916
Anton Romanov Avatar asked Jun 16 '26 06:06

Anton Romanov


2 Answers

You can use a little map function to extract the array age

const inputObject = {
  "userList":
  [{
    "name": "Bob",
    "age": 28
  },{
    "name": "Tom",
    "age": 45
  },{
    "name": "Alice",
    "age": 32
  }]
  };
  
  const output = inputObject.userList.map(user => user.age);
  console.log(output);
like image 163
Melchia Avatar answered Jun 18 '26 19:06

Melchia


Say arrayObject is the object you have, following should do it. map will return a new array that will be assigned to ageArray.

let ageArray = arrayObject.userList.map(e => e.age)
like image 22
Aragorn Avatar answered Jun 18 '26 21:06

Aragorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!