4

So I got a JSON array like this one:

"robots": [
    {
        "id": 1,
        "name": "foo",
        "last_connection": "2017-03-18 14:25:36"
    },{
        "id": 3,
        "name": "bar",
        "last_connection": "2017-03-19 17:28:39"
    },{
        "id": 8,
        "name": "foobar",
        "last_connection": "2017-04-18 11:22:33"
    }
]

Is there is simple way to get an array of ids from all my robots without doing a for loop over my array?

ids = [1, 3, 8]
ndelanou
  • 523
  • 5
  • 16

1 Answers1

11

Yes, using the Array.map method.

const ids = robots.map(robot => robot.id);

ids will now be [1, 3, 8].

Aron
  • 8,696
  • 6
  • 33
  • 59
  • 2
    Please do not answer this basic questions. There is a very high chance they have been answered before. Search such links and share their url and mark them as duplicate – Rajesh May 16 '17 at 08:07
  • 1
    What's wrong with answering a basic question if it's literally a one-liner? – Aron May 16 '17 at 08:08
  • Whats wrong is you are duplicating content. Old posts have different methods to achieve output, have discussions in comment and more importantly explanations which your answer is missing. – Rajesh May 16 '17 at 08:10