Given an array of objects with ids:
array: [
{id: 3, value: 'foo'},
{id: 6, value: 'bar'},
{id: 9, value: 'baz'},
// ...
],
What is the shortest way to return a single object from the array that matches an id
?
Keep in mind that the array can be undefined
while the model is loading. In that case, the computed property should also return undefined
.
This works:
_test : computed.filterBy('array', 'id', 6),
test : computed.alias('_test.firstObject')
But it is not pretty, using a temporary variable.
This is better:
test : computed('array.[]', function() {
let array = this.get('array')
if (array) return array.find(el => el.id == 6)
})
But it is not pretty, because it uses 4 lines.
Ember contains a lot of syntactic sugar, but I haven't figured out how to shrink this.
The methods filter
and filterBy
will reduce an array to just the list of items you're filtering to.
If you want a single item from the list, use find
or findBy
.
In your case, you'll use the following.
test: computed('array.[]', function() {
return this.getWithDefault('array',[])
.findBy('id',6)
})
When you're done, this.get('test')
will return {id: 6, value: 'bar'}
More information can be found in the documentation for MutableArray