Ember.js计算得出:从数组返回单个对象的最短方法

时间:2018-07-11 14:53:31

标签: javascript ember.js computed-observable

给出具有ID的对象数组:

array: [
    {id: 3, value: 'foo'},
    {id: 6, value: 'bar'},
    {id: 9, value: 'baz'},
    // ...
],

从与id匹配的数组中返回单个对象的最短方法是什么? 请记住,在加载模型时,数组可以为undefined。在这种情况下,计算出的属性还应该返回undefined

这有效:

_test       : computed.filterBy('array', 'id', 6),
test        : computed.alias('_test.firstObject')

但这不是一个漂亮的东西,使用一个临时变量。

这更好:

test        : computed('array.[]', function() {
    let array = this.get('array')
    if (array) return array.find(el => el.id == 6)
})

但这并不漂亮,因为它使用4行。

Ember包含很多语法糖,但是我还没有弄清楚如何缩小它。

1 个答案:

答案 0 :(得分:1)

方法filterfilterBy会将数组缩小为仅过滤到的项目列表。

如果要从列表中选择一项,请使用findfindBy

在您的情况下,您将使用以下内容。

test: computed('array.[]', function() {
    return this.getWithDefault('array',[])
        .findBy('id',6)
})

完成后,this.get('test')将返回{id: 6, value: 'bar'}

有关更多信息,请参见MutableArray的文档

相关问题