如何捕获数组中的匹配计数值?

我有一个x可以具有以下值的数组:


0: {status: "completed", count: 2}

1: {status: "pending", count: 3}

现在,如果状态匹配,pending那么我想捕获相应的值count。


我写了以下代码:


if (x?.length) {

PendingCount = x[1].count;

completedCount = x[0].count;

}

这并不总是给出所需的输出,因为pending状态不一定总是在x[0]


一只斗牛犬
浏览 104回答 4
4回答

潇潇雨雨

我会使用 Array.prototype.find 来查找具有待定状态的项目,然后获取其 count 属性,如下所示:const { count } = x.find(({ status } = {}) => status === 'pending') || {}:如果存在未决状态,这将为您提供计数,如果不存在,则为未定义状态。我在这里使用了解构和默认语法,如果您不熟悉它们,请查看我链接的文章。

森栏

您可以使用过滤器,将找到所有具有待处理状态的元素const data = [{    status: "completed",    count: 2  },  {    status: "pending",    count: 3  }];const pending = data.filter(s => s.status === "pending");console.log(pending.length ? "got pending" : "no pending")console.log(pending.map(i=>i.count))

繁星点点滴滴

如果保证只有 1 个元素带有 "pending" status,那么使用Array.prototype.find根据其属性值查找元素似乎是合适的status:const pendingCount = [{  status: "completed",  count: 2}, {  status: "pending",  count: 3}].find(el => el.status === "pending").count;console.dir(`pending count = ${pendingCount}`);如果数组中有多个“待定”项目并且您需要获取所有项目的总和,那么使用 Array.prototype.filter (删除所有非“待定”项目)然后使用Array.prototype 可能最有意义。减少结果filter以添加counts。const pendingSum = [{    status: "completed",    count: 2  }, {    status: "pending",    count: 3  }, {    status: "pending",    count: 5  }, {    status: "pending",    count: 5  }]  .filter(el => el.status === "pending")  .reduce((sum, el) => sum += el.count, 0);console.dir(`sum of pending items count = ${pendingSum}`);

蝴蝶刀刀

const array = [  {status: "completed", count: 2},  {status: "pending", count: 3}];const pending = array.find(s => s.status === "pending");if (pending) {   // Do whatever you want.}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript