mercredi 11 juillet 2018

Ember.js computed: Shortest way to return single object from array

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.




Aucun commentaire:

Enregistrer un commentaire