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,
}]
}
]
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
.
You can use destructuring assignment to simplify this if you have ES6:
const { subscriptionsState: { subscriptions } } = state
this.subscription = subscriptions.find(s => s.id === subscriptionId)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.