1

sorry for the newbie question. Using lodash, how to get an array with all nested "machineries" entries from this API response ?

{
  "areas": [
    {
      "name": "BAR 1",
      "machineries": [
        {
          "_id": "stand BAR 1.1"
        }
      ]
    },
    {
      "name": "BAR 2",
      "machineries": [
        {
          "_id": "stand BAR 2.1"
        },
        {
          "_id": "stand BAR 2.2"
        }
      ]
    }
  ]
}

Using above data I would return 3 entries:

[
    {
        "_id": "stand BAR 1.1"
    },
    {
        "_id": "stand BAR 2.1"
    },
    {
        "_id": "stand BAR 2.2"
    }
]

Thank's

1 Answer 1

0

You can use Array.prototype.flatMap() combined with Array.prototype.map() and Destructuring assignment:

const data = {areas: [{name: 'BAR 1',machineries: [{_id: 'stand BAR 1.1',},],},{name: 'BAR 2',machineries: [{_id: 'stand BAR 2.1',},{_id: 'stand BAR 2.2',},],},],}

const result = data.areas.flatMap(({ machineries: m }) => m.map(({ _id }) => ({ _id })))

console.log(result)

Sign up to request clarification or add additional context in comments.

1 Comment

@ClaudioBarca good to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.