Rajesh Kumar Duraisamy
Rajesh Kumar Duraisamy

Reputation: 797

parse all the values from the json array using typescript

I have a json array like below, I need to get all the values from below array and need to form a new array of array objects

But I cannot use any model files to achieve this. Not sure how to do this in typescript.

Please help me on this.

[
  {
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "age": "25"
  },
  {
    "firstName": "john",
    "lastName": "david",
    "age": "26"
  }
]

I need to output like

[["Rajesh","Kumar","25"],["john","david","26"]]

Upvotes: 1

Views: 3567

Answers (4)

Victoria
Victoria

Reputation: 335

You can try this:

let newArrObj: any[] = []; 

// objects - your array of objects

for (let obj in objects) {

  let objArray= []; 
  objArray.push(obj.firstName)
  objArray.push(obj.lastName)
  objArray.push(obj.age)
  
  newArrObj.push(objArray);
 }
 
 console.log("Result newArrObj: ", newArrObj);

Upvotes: 0

RishiMath
RishiMath

Reputation: 193

So, what you want to do is to map all the values in the array using <Array>.map. Then you can return the object as an Array in 2 ways, first is using <Object>.values or by just doing [obj.firstName, obj.lastName, obj.age]

You could try Looping through the array and change the values as well using a for loop, but that it really verbose. I'd recommend the 1st approach, since that's more dynamic in this case.

So the resulting code will be

let data = [
  {
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "age": "25"
  },
  {
    "firstName": "john",
    "lastName": "david",
    "age": "26"
  }
];
// I'm assigning the value to the variable called data in this case

data = data.map(item => Object.values(item));

// Now the value of data is the array you want it to be

Now you can follow the other approaches as I specified, however this is the least verbose way to go around.

Upvotes: 3

tsamridh86
tsamridh86

Reputation: 1496

Since you have limited elements inside each object you could do:

const collections = [
  {
    firstName: 'Rajesh',
    lastName: 'Kumar',
    age: '25'
  },
  {
    firstName: 'john',
    lastName: 'david',
    age: '26'
  }
]

const answer = collections.map(c => [c.firstName, c.lastName, c.age])
console.log(answer)

Upvotes: 0

Erez Shlomo
Erez Shlomo

Reputation: 2272

This will give you what you are looking for

const array = [
  {
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "age": "25"
  },
  {
    "firstName": "john",
    "lastName": "david",
    "age": "26"
  }
];

// Under result you will have the required array
const result = a.map(x => [Object.keys(x).map(key => x[key])])

// Or, explicit
const result = array.map(x => [x.firstName,x.lastName,x.age])

Upvotes: 0

Related Questions