【发布时间】:2018-02-20 01:21:03
【问题描述】:
我有一个带有其他数组的对象。当主数组匹配 RazaoSocial:"AAS" 或 Produtos:[{Descricao:"AAS"}]
时,我需要过滤这是我的代码:
var input = [
{
RazaoSocial: 'AAS',
Produtos: [
{ DescricaoProduto: 'XXX', id:12, other:"other text" },
{ DescricaoProduto: 'YYY', id:12, other:"other text" }
]
},
{
RazaoSocial: 'I found you',
Produtos: [
{ DescricaoProduto: 'AAS', id:12, other:"other text" },
{ DescricaoProduto: 'Miss8', id:12, other:"other text" },
{ DescricaoProduto: 'Miss8', id:12, other:"other text" },
{ DescricaoProduto: 'Miss8', id:99, other:"other text" }
]
},
{
RazaoSocial: 'bla',
Produtos: [
{ DescricaoProduto: 'AB', id:12, other:"other text" },
{ DescricaoProduto: 'CD', id:12, other:"other text" },
]
},
];
var res = input.filter(function f(o) {
if (o.RazaoSocial.includes("AAS")) return true
if (o.Produtos.DescricaoProduto) {
console.log(o.Produtos);
return (o.Produtos = o.Produtos.filter(f)).length
}
})
console.log(JSON.stringify(res, null, 2));
//结果
[
{
"RazaoSocial": "AAS",
"Produtos": [
{
"DescricaoProduto": "XXX",
"id": 12,
"other": "other text"
},
{
"DescricaoProduto": "YYYAAS",
"id": 12,
"other": "other text"
}
]
}
]
为什么没有返回带有“我找到你”的对象?我在努力
[
{
RazaoSocial: 'AAS',
Produtos: [
{ DescricaoProduto: 'XXX', id: 12, other: "other text" },
{ DescricaoProduto: 'YYY', id: 12, other: "other text" }
]
},
{
RazaoSocial: 'I found you',
Produtos: [
{ DescricaoProduto: 'AAS', id: 12, other: "other text" },
{ DescricaoProduto: 'Miss8', id: 12, other: "other text" },
{ DescricaoProduto: 'Miss8', id: 12, other: "other text" },
{ DescricaoProduto: 'Miss8', id: 99, other: "other text" }
]
}
]
我尝试了其中的示例,但没有成功。 Recursively filter array of objects
我做错了什么?
感谢您的帮助。
【问题讨论】:
标签: javascript arrays recursion filter