gpt4 book ai didi

javascript - 如何按对象数组中的数组属性进行过滤

转载 作者:行者123 更新时间:2023-12-02 17:28:38 25 4
gpt4 key购买 nike

我有一个像这样初始化的集合:

var invoices = new Array();
var invoice = new Invoice();
invoice.number = "123";
invoice.date = "2016-05-03";
invoice.amount = "100";
var products = new Products();

var product = new Product();
product.code = "A";
product.name = "bar";
products.push(product);

var product2 = new Product();
product2.code = "B";
product2.name = "foo";
products.push(product2);

invoice.products = products;

现在我必须像这样按发票的属性进行过滤。

var filtered = invoices.filter(function(invoice){
return invoice.number == "123";
});

但现在我想获取与编号和产品名称匹配的发票

我该怎么做

var filtered = invoices.filter(function(invoice){
return invoice.number == "123"
// && invoice.products "name" == "foo"; //<-- At this level how can I filter?
});

最佳答案

使用Array.some检查是否存在具有所需名称的产品:

var filtered = invoices.filter(function(invoice){
return invoice.number == "123" && invoice.products.some(function(prod) {
return prod.name === 'foo';
});
});

与使用Array.filter并检查结果数组的长度不同,这完全避免了创建临时数组和短路;一旦发现命中,它就会立即返回 true。

关于javascript - 如何按对象数组中的数组属性进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com