【发布时间】:2022-02-03 03:06:42
【问题描述】:
我正在构建一个搜索功能,我需要在其中搜索要通过部分文本找到的特定值。 所以我有一个示例对象:
const data = [
{
org_name: "A PFS COUNTRY TESTS",
clients: [
{
name: "Abu Dhabi",
type: "Yacht",
currency: "EUR",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
},
{
name: "Australia",
type: "Yacht",
currency: "AUD",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
},
{
name: "Bermuda",
type: "Yacht",
currency: "EUR",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
}
]
},
{
org_name: "Music Tours",
clients: [
{
name: "Music Demo",
type: "Office",
currency: "GBP",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
},
{
name: "Summer Tour",
type: "Office",
currency: "GBP",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
},
{
name: "Winter Tour",
type: "Yacht",
currency: "USD",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
}
]
},
{
org_name: "Dariusz Sandbox 1",
clients: [
{
name: "Dariusz Test Client 1",
type: "Yacht",
currency: "EUR",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
},
{
name: "Dariusz Test Client 2",
type: "House",
currency: "GBP",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
},
{
name: "Dariusz Test Client 3",
type: "Aircraft",
currency: "USD",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
}
]
},
{
org_name: "Dariusz Sandbox 2",
clients: [
{
name: "Dariusz Test Client 1",
type: "Yacht",
currency: "EUR",
notifications: {
for_action: 0,
for_attention: 0
},
unpaid_invoices: {
total: 0,
ok_to_pay: 0,
reviewed: 0
}
}
]
}
];
因此,如果我正在寻找“Dar”,我应该接收仅包含 org_name 对象的数组,这些对象的客户端的名称值中包含“Dar”。
到目前为止我的解决方案是:
const newData = data.map((el) => {
const filtered = el.clients.filter((client) => {
if (client.name.includes("Dar")) {
return client;
}
});
if (filtered.length > 0) {
return { org_name: el.org_name, clients: filtered };
}
});
console.log("newData is", newData);
但我得到的是[undefined, undefined, Object, Object]
而不是[Object, Object]
【问题讨论】:
标签: javascript arrays object search filtering