gpt4 book ai didi

javascript - 使用 Typescript 中的条件对象过滤嵌套数组的数组

转载 作者:行者123 更新时间:2023-11-30 20:02:19 25 4
gpt4 key购买 nike

我有如下所示的对象数组(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));

通过 tests 获取所有 data "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,
},
]
}
]

最佳答案

您走在正确的轨道上,但是您正在从外部 filter 回调返回内部 filter 结果(一个数组)。数组是真实的,因此您保留了所有内容。

您需要分两步处理每个外部对象:

  1. 过滤其测试,以及

  2. 如果 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;
}

关于javascript - 使用 Typescript 中的条件对象过滤嵌套数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242296/

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