我在过滤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"
}
]
}
]
我使用了嵌套过滤器,但它没有用。我怎样才能得到结果?
答案 0 :(得分:1)
您需要将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);