1

How can i find a single object which is nested deeply in an array? This is the code which works. But [0] isnt really save when it returns null or an empty array.

this.subscription = state.subscriptionsState.subscriptions
    .map(subs => subs.subscriptions.find(sub => sub.id === subscriptionId))[0];

Is there a better / nicer way?

edit: input data:

state.subscriptionsState.subscriptions = [
    {
        "name": "name",
        "type": "type",
        "subscriptions": [{
            "id": 123456,
        }]
    }
]
4
  • You need to add your input data. Commented Mar 19, 2018 at 15:10
  • @NicholasKyriakides done. Commented Mar 19, 2018 at 15:13
  • .map()[0] can be replaced by .find() Commented Mar 19, 2018 at 15:19
  • @Troopers that doesn't work, then it returns the "parent" subscription. With a find instead of map i need to return a bool in the "second" find. Commented Mar 19, 2018 at 15:23

2 Answers 2

4

You can reduce you base Array into a 1D Array containing only the subscriptions.

From then on it's a simple .find() which returns undefined if nothing was found, or the subscription if something was found.

'use strict'

const items =[
  {
    "name": "name",
    "type": "type",
    "subscriptions": [{
      "id": 123456,
    }]
  }
]

const result = items
  .reduce((arr, item) => arr.concat(item.subscriptions), [])
  .find(sub => sub.id === 123456)

console.log(result)

This should throw no errors if the base Array is empty, or if any 1st level item subscriptions Array property is empty, it would just return undefined.

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

Comments

0

You can use destructuring assignment to simplify this if you have ES6:

const { subscriptionsState: { subscriptions } } = state

this.subscription = subscriptions.find(s => s.id === subscriptionId)

Comments

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.