-2

I have an array of objects like this:

var myArray = [{
    key: 2,
    value: 10,
},
{
    key: 5,
    value: 4,
},
{
    key: 3,
    value: 8,
},
{
    key: 12,
    value: 4,
}];

How is the most elegant way to convert this array in other just with the key numbers: [2,5,3,12]?

FabianoLothor
  • 2,479
  • 4
  • 23
  • 35

2 Answers2

1

Use .map:

const myKeys = myArray.map(i => i.key);
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
1

Use array.map

var myArray = [{
    key: 2,
    value: 10,
},
{
    key: 5,
    value: 4,
},
{
    key: 3,
    value: 8,
},
{
    key: 12,
    value: 4,
}];

console.log(myArray.map(a => a.key));
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376