【发布时间】:2022-01-13 16:33:52
【问题描述】:
我有以下对象数组;然而,这可能是任何未知的键/值并且可以无限嵌套,现在这是一个测试示例:
[
{
"reference_id": "R123",
"customer": "Person 1",
"customer_email": "person1@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
{
"reference_id": "R1234",
"customer": "Person 2",
"customer_email": "person2@email.com",
"location": "USA",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
{
"reference_id": "R12345",
"customer": "Person 3",
"customer_email": "person3@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
}
]
我目前的实现如下:
const selected = [
{
term: 'Company 1',
column: 'provider',
},
{
term: 'Person 1',
column: 'customer',
},
];
const recursivelyFilterByValue = () => (value) => selected.every((item) => {
if (!value) return false;
if (typeof value === 'string') {
// console.log('value', value === item.term);
return value === item.term;
}
if (Array.isArray(value)) {
return value.some(this.recursivelyFilterByValue());
}
if (typeof value === 'object') {
return Object.values(value).some(this.recursivelyFilterByValue());
}
return false;
});
const results = data.filter(recursivelyFilterByValue());
基本上,我将添加到“选定”数组中,然后使用它来过滤数据数组。我确实想确保键与“列”匹配,但我还没有添加。
对于上面的输入,我希望输出以下内容:
[
{
"reference_id": "R123",
"customer": "Person 1",
"customer_email": "person1@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
]
但是输出数组是空的。如果我只搜索一个术语(从所选数组中删除除一个术语之外的所有术语),则该术语的输出是正确的,但是任何后续术语都会返回一个空白数组。
我想知道我对 .some() 的使用是否是问题,但是更改它会导致太多递归错误。
本质上,只要在所选数组中的所有条件都存在键:值匹配项,无论其子对象的任何级别,我都想返回原始父对象。
任何指导将不胜感激,谢谢。
【问题讨论】:
-
我有这个权利吗?您有一个(可能是动态的)条件,该条件表示一个对象要么具有
provider属性,值为"Customer 1",要么具有(递归)后代对象。并且您有关于customer和"Person 1"的第二个条件,并且您正在寻找满足这两个(或所有)这些条件的对象。这是否描述了您正在尝试做的事情? -
@ScottSauyet 没错。本质上,我想返回每个条件至少有一个匹配项的原始/根父对象(或其后代具有)。父项必须与数组中的每个条件都匹配,然后才能返回,因此我们需要搜索所有后代以找到每个条件的至少一个匹配项。条件将始终在数据中至少有一个匹配项,因为条件是根据剩余数据的匹配顺序添加的。
-
如果您知道只有一个匹配项 - 或者即使您知道最多有一个匹配项 - 那么您可以将我的答案中的
filter替换为find。
标签: javascript arrays recursion multidimensional-array filter