如何使用.filter()按对象内的对象进行过滤?

时间:2019-06-17 14:48:36

标签: javascript

我有一个大的invoices对象,其中包含许多单独的invoice对象。我只想过滤任何invoice属性中包含搜索条件的invoice对象。

我尝试使用.forEach和.filter的组合,但我认为我不完全了解如何将它们链接在一起

const invoices = { 1: {OrderID: "123", InvoiceID: "ABD", InvoiceDate: "2015-03-08T00:00:00-05:00", InvoiceAmount: "54061"},
2: {OrderID: "321", InvoiceID: "ABC", InvoiceDate: "2015-03-08T00:00:00-05:00", InvoiceAmount: "124031"}}

psudeo-code:

for each invoice in invoices
for each property in invoice
check if property value equals search input
return array of invoices.keys

在我的示例中,如果我的搜索输入=“ ABC”,我想返回一个数组[2]。如果有多个invoice,其中InvoiceID ==“ ABC”,那么我期望并用所有这些键进行排列。

1 个答案:

答案 0 :(得分:1)

问题是您没有数组。你有一个对象。

  

正如凯文·毕博莱特(KévinBibollet)所述,forEachfilter不适用于对象,因为它是为数组而制成的。

解决方案可能是遍历您的对象,通过includes检查并将它们推到输出数组,就像我在这里所做的那样:

const invoices = { 
  1: {OrderID: "123", InvoiceID: "ABD", InvoiceDate: "2015-03-08T00:00:00-05:00", InvoiceAmount: "54061"},
  2: {OrderID: "321", InvoiceID: "ABC", InvoiceDate: "2015-03-08T00:00:00-05:00", InvoiceAmount: "124031"}
}

function search(str) {
  var output = [];
  
  // loop through invoices
  for(var invoice in invoices){
    // loop through actual invoice
    for(var key in invoices[invoice]){
      // check if actual value includes the searchstring 
      if(invoices[invoice][key].includes(str)){
        // push into output-array
        output.push(invoices[invoice]);
        // break the look to avoid pushing it again if there are more matches
        break; 
      }
    }
  }
  
  // return the output-array
  return output;
}

console.log(search('ABC'));