我有如下所示的对象数组(Json格式)
var datas = [
{
"Id": "1",
// Here 10 fields
"tests": [
{
"id":"1-1",
"isSelected": true,
},
{
"id":"1-2",
"isSelected": false,
},
]
},
{
"Id": "2",
// Here 10 fields
"tests": [
{
"id":"2-1",
"isSelected": true,
},
{
"id":"2-2",
"isSelected": true,
},
]
},
{
"Id": "3",
// Here 10 fields
"tests": [
{
"id":"3-1",
"isSelected": false,
},
{
"id":"3-2",
"isSelected": false,
},
]
}
]
我尝试如下
var filteredData = datas.filter( t => t.tests.filter(o => o.isSelected));
获取所有具有测试值为"isSelected"
的数据是true
,它不起作用。反正有没有获取以下格式的数据。
[
{
"Id": "1",
// Here 10 fields
"t": [
{
"id":"1-1",
"isSelected": true,
}
]
},
{
"Id": "2",
// Here 10 fields
"tests": [
{
"id":"2-1",
"isSelected": true,
},
{
"id":"2-2",
"isSelected": true,
},
]
}
]
答案 0 :(得分:1)
您在正确的轨道上,但是您正在从外部filter
回调中返回内部filter
的结果(数组)。数组是真实的,因此您要保留所有内容。
您需要分两个步骤处理每个外部对象:
过滤其tests
和
如果tests
为空,则将其完全过滤掉
所以:
var filteredData = datas.filter(t => {
t.tests = t.tests.filter(o => o.isSelected);
return t.tests.length !== 0;
});
var datas = [
{
"Id": "1",
// Here 10 fields
"tests": [
{
"id":"1-1",
"isSelected": true,
},
{
"id":"1-2",
"isSelected": false,
},
]
},
{
"Id": "2",
// Here 10 fields
"tests": [
{
"id":"2-1",
"isSelected": true,
},
{
"id":"2-2",
"isSelected": true,
},
]
},
{
"Id": "3",
// Here 10 fields
"tests": [
{
"id":"3-1",
"isSelected": false,
},
{
"id":"3-2",
"isSelected": false,
},
]
}
]
var filteredData = datas.filter(t => {
t.tests = t.tests.filter(o => o.isSelected);
return t.tests.length !== 0;
});
console.log(filteredData);
.as-console-wrapper {
max-height: 100% !important;
}
或者如果您真的想要简洁的箭头功能:
所以:
var filteredData = datas.filter(t =>
(t.tests = t.tests.filter(o => o.isSelected)).length !== 0
);
var datas = [
{
"Id": "1",
// Here 10 fields
"tests": [
{
"id":"1-1",
"isSelected": true,
},
{
"id":"1-2",
"isSelected": false,
},
]
},
{
"Id": "2",
// Here 10 fields
"tests": [
{
"id":"2-1",
"isSelected": true,
},
{
"id":"2-2",
"isSelected": true,
},
]
},
{
"Id": "3",
// Here 10 fields
"tests": [
{
"id":"3-1",
"isSelected": false,
},
{
"id":"3-2",
"isSelected": false,
},
]
}
]
var filteredData = datas.filter(t =>
(t.tests = t.tests.filter(o => o.isSelected)).length !== 0
);
console.log(filteredData);
.as-console-wrapper {
max-height: 100% !important;
}