【发布时间】:2019-07-09 20:11:04
【问题描述】:
我有一个包含嵌套对象的数组。像这样的:
const results = [
{
general: {
orderID: '5567',
created: 1548765626101,
status: 'new'
},
company: {
companyName: 'company x',
companyEmail: 'info@companyx.com',
companyContact: 'John Doe'
},
customer: {
customerName: 'Jane Doe',
customerEmail: 'janedoe@email.com'
},
products: [
{
productID: 4765756,
productName: 'Product x',
productDescription: 'Description for product x'
},
{
productID: 4767839,
productName: 'Product y',
productDescription: 'Description for product y'
}
],
payment: {
price: 1000,
method: 'cash'
}
},
]
(为了让它有点结构化,我只为这个问题插入了一个结果对象。但假设结果数组中有 100 个元素。)
用户可以输入搜索词并选中/取消选中包含或排除这些键的键。键被硬编码在一个列表中。
例如。用户键入“jane”并检查 customerName 和 customerEmail 作为想要搜索的键。或者用户输入“x”并检查产品名称。
如何动态搜索这些选中的键?我已经在数组中有选定的键。
所以对于第一个例子,我有['customerName', 'customerEmail']。
第二个是['productName']
我之前使用过array.filter() 硬编码键,但我不知道如何过滤这些动态键。
有人可以帮我分解不同的步骤吗?我正在使用 es6,没有外部库。
【问题讨论】:
-
你想从搜索中返回什么?匹配的整个顶级对象?
-
@GabrielePetrioli 是的,一个包含所有匹配(顶级)对象的数组
标签: javascript arrays object filter ecmascript-6