gpt4 book ai didi

javascript - 双过滤器在 JSON 数组中不起作用

转载 作者:行者123 更新时间:2023-11-29 15:15:40 25 4
gpt4 key购买 nike

我在过滤 JSON 数组时遇到了一些问题。这是我想要的代码和结果,所以请帮我过滤一下。

var all = [
{
data : "test1",
dataArray : [
{
name : "abc",
status : true,
address: "test"
}, {
name : "xyz",
status : false,
address: "test"
}, {
name : "pqr",
status : true,
address: "test"
},
]
},
{
data : "test2",
dataArray : [
{
name : "abc",
status : true,
address: "test"
}, {
name : "xyz",
status : false,
address: "test"
}, {
name : "pqr",
status : false,
address: "test"
},
]
},
{
data : "test3",
dataArray : [
{
name : "abc",
status : false,
}, {
name : "xyz",
status : false,
}, {
name : "pqr",
status : true,
},
]
}
]

console.log(JSON.stringify(all.filter((a)=>a.dataArray.filter((b)=>b.status==true)),null,2));

想要这样的结果:
只有状态为 true 的数据,但我不知道为什么过滤器返回所有 JSON 数据。嵌套过滤器有什么问题吗??

a = [
{
data : "test1",
dataArray : [
{
status : true,
address: "test"
},{
status : true,
address: "test"
},
]
},
{
data : "test2",
dataArray : [
{
status : true,
address: "test"
},
]
},
{
data : "test3",
dataArray : [
{
status : true,
address: "test"
}, {
status : true,
address: "test"
}
]
}
]

我使用了嵌套过滤器,但它不起作用。我怎样才能得到结果?

最佳答案

您需要将filter应用于dataArray,而不是all

all.forEach( s => s.dataArray = s.dataArray.filter( t => t.status ) )

注意事项

  • 此解决方案会改变 all 数组,因此如果您不想改变 - 首先创建 all 的深拷贝。

演示

var all = [{
data: "test1",
dataArray: [{
name: "abc",
status: true,
address: "test"
}, {
name: "xyz",
status: false,
address: "test"
}, {
name: "pqr",
status: true,
address: "test"
}, ]
},
{
data: "test2",
dataArray: [{
name: "abc",
status: true,
address: "test"
}, {
name: "xyz",
status: false,
address: "test"
}, {
name: "pqr",
status: false,
address: "test"
}, ]
},
{
data: "test3",
dataArray: [{
name: "abc",
status: false,
}, {
name: "xyz",
status: false,
}, {
name: "pqr",
status: true,
}, ]
}
];

all.forEach(s => s.dataArray = s.dataArray.filter(t => t.status))

console.log(all);

关于javascript - 双过滤器在 JSON 数组中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49569570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com