我正在尝试过滤具有子数组的数组。 我想按子数组过滤我的数组 我的数组看起来像这样:
var Branches = [
{
Name: 'branch1',
Screens: [
{
Name: 'Screen1',
Player: {
Status: 0
}
},
{
Name: 'Screen2',
Player: {
Status: 1
}
}
]
},
{
Name: 'branch2',
Screens: [
{
Name: 'Screen1',
Player: {
Status: 0
}
},
{
Name: 'Screen2',
Player: {
Status: 1
}
}
]
}]
我已经使用linq.js进行了尝试
var param = 1
var result = Enumerable.From(Branches).Where(function (d) {
return (d.Screen.some(x => x.Player.Status === param))
}).ToArray();
但是此代码olso从每个分支获得状态0
我只想从每个分支获取状态= 1
预期:
[
{
Name: 'branch1',
Screens: [
{
Name: 'Screen2',
Player: {
Status: 1
}
}
]
},
{
Name: 'branch2',
Screens: [
{
Name: 'Screen2',
Player: {
Status: 1
}
}
]
}
]
谢谢;)
答案 0 :(得分:0)
var Branches = [
{
Name: "branch1",
Screens: [
{
Name: "Screen1",
Player: {
Status: 0
}
},
{
Name: "Screen2",
Player: {
Status: 1
}
}
]
},
{
Name: "branch2",
Screens: [
{
Name: "Screen1",
Player: {
Status: 0
}
},
{
Name: "Screen2",
Player: {
Status: 1
}
}
]
}
];
var param = 1;
console.log(Branches.reduce( (p, c) => ((c.Screens = c.Screens
.filter(s => s.Player.Status == param)).length && p.push(c), p), []
));
答案 1 :(得分:0)
您可以映射对象并过滤Screens
。
var branches = [{ Name: 'branch1', Screens: [{ Name: 'Screen1', Player: { Status: 0 } }, { Name: 'Screen2', Player: { Status: 1 } }] }, { Name: 'branch2', Screens: [{ Name: 'Screen1', Player: { Status: 0 } }, { Name: 'Screen2', Player: { Status: 1 } }] }],
wanted = 1,
result = branches.map(({ Screens, ...o }) => ({ ...o, Screens: Screens.filter(({ Player: { Status } }) => Status === wanted) }));
console.log(result);
答案 2 :(得分:0)
使用linq.js,您需要将其查看为选择具有一组经过过滤的屏幕的分支。您可能不想修改现有项目,因此应该创建新项目。
let status = 1;
let result = Enumerable.From(Branches)
.Select(({Screens, ...rest}) => ({
Screens: Enumerable.From(Screens)
.Where(({Player:{Status}}) => Status === status)
.ToArray(),
...rest
})).ToArray();
尽管妮娜(Nina)表示,您实际上并不需要它,因为Array.map
和Array.filter
可以解决这个问题。