-2

I receive a JSON from a REST service which is represented by the following JavaScript object:

[
    {
        name: 'demo1',
        contentType: 'text/plain',
        lang: 'en-US',
        type: 'FILE',
        revision: 5
    },
    {
        name: 'demo2',
        contentType: 'text/plain',
        lang: 'en-US',
        type: 'FILE',
        revision: 29
    }
]

From this object I'd like to extract all values from the name key, i.e. in the end I have a new array with the values [demo1, demo2].

I tried running a for-loop over Object.entries() but this seems somewaht tedious. There is probably a much easier way.

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

1 Answers1

1

Use .map() and an arrow function.

const theArray = [
    {
        name: 'demo1',
        contentType: 'text/plain',
        lang: 'en-US',
        type: 'FILE',
        revision: 5
    },
    {
        name: 'demo2',
        contentType: 'text/plain',
        lang: 'en-US',
        type: 'FILE',
        revision: 29
    }
]

console.log(theArray.map(obj => obj.name))
WillD
  • 5,170
  • 6
  • 27
  • 56
  • 2
    This is an often-asked duplicate of [this question](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array). – T.J. Crowder May 01 '20 at 14:07