-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,752
  • 4
  • 25
  • 39

2 Answers2

1

Use .map:

const myKeys = myArray.map(i => i.key);
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
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
  • 216,225
  • 63
  • 350
  • 396