Ahsan Alam Siddiqui
Ahsan Alam Siddiqui

Reputation: 71

how to push all objects keys to a separate array in array using angular or javascript?

I have array of objects like this

let array = [
 {'name' : 'Jack', 'age':23},
 {'name': 'Robin', 'age':25}
];

and I want an array like this

[
 ['Jack',23],
 ['Robin',25]
]

I tried this code

var myArr = []; 

var input = [
  {name : 'Jack', age : 23},
  {name : 'Robin', age : 25}
];

input.forEach((item,index)=>{
  for (var k in item) { 
    myArr.push(item[k]);
  }
})

But it is producing result like this

["Jack", 23, "Robin", 25]

Upvotes: 0

Views: 1038

Answers (3)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

let array = [
 {'name' : 'Jack', 'age':23},
 {'name': 'Robin', 'age':25}
];

arrayOfValues = array.map(({name, age})=> ([name, age]))

console.log(arrayOfValues)

@HMR Thank you very much for sharing the valuable information.

The order in which you get the values in Object.values or Object.keys or for ... in or for ... of from an object (other than a Map) is not guaranteed and there is no specification in JS for the order.

More Information

Upvotes: 4

Mohammad Usman
Mohammad Usman

Reputation: 39392

Simply pass Object.values as callback to .map():

let array = [
 {'name' : 'Jack', 'age':23},
 {'name': 'Robin', 'age':25}
];

let result = array.map(Object.values);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Nitish Narang
Nitish Narang

Reputation: 4184

This would be Array.map and Object.values like below

let array = [
 {'name' : 'Jack', 'age':23},
 {'name': 'Robin', 'age':25}
];

let res = array.map(d => Object.values(d))

console.log(res)

Upvotes: 2

Related Questions