查找集合中是否存在具有值的项

Find if item in collection with value exists

本文关键字:存在 集合 是否 查找      更新时间:2024-05-03

首先,这里是我非常简单的组件:

var RenewedLoanModal = new Vue ({
      el: '#myModal',
      data:
        {
          responses: []
        }
      });

responses由ajax调用填充,它是一个对象数组。结构如下:

responses: [
    {error: 'foo', message: 'foo', id: 'foo', success: true},
    {error: 'bar', message: 'bar', id: 'bar', success: false},
    ...
]

我想知道这些对象中是否有一个有success: false,但我无论如何都没有找到来检查它

有没有一种方法可以在方法中而不是在视图渲染中迭代responses集合?或者v-if测试?

有很多方法可以通过项的属性来检查项是否存在于集合中。

纯Javascript

只使用纯javascript可以做的第一件事是:

var success = false
for (var i = 0; i < responses.lenth; i++) {
  if (responses[i].success === true) success = true
}

ECMAScript 6

你可以在ES6中这样做:

var success = responses.reduce((prev, cur) => prev || cur.success, false)

功能性编程

另一种更具声明性的方法是使用Ramda.js库:

// if 'any' of the elements satisfy the predicate
var success = R.any(response => response.success === true)(responses)
// or more briefly
var success = R.any(response => response.success)(responses)

在Vue.js中连接

在创建了一个具有上述返回结果的计算属性之后,如果您想有条件地显示某些内容,可以将其连接到v-ifv-show

如果可能的话,我会使用:

data: { hadError: false, responses: [] } 并让addResponse(data,resp)完成以下工作: if(resp.success === false) data.hadError = true; data.responses.push(resp);

否则: for(i=0; i<responses.length; i++) { if(response[i].success === false) ..... }