4 回答

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

TA贡献1810条经验 获得超5个赞
您可以使用过滤器,将找到所有具有待处理状态的元素
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))

TA贡献1803条经验 获得超3个赞
如果保证只有 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
以添加count
s。
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}`);

TA贡献1801条经验 获得超8个赞
const array = [
{status: "completed", count: 2},
{status: "pending", count: 3}
];
const pending = array.find(s => s.status === "pending");
if (pending) {
// Do whatever you want.
}
添加回答
举报