我有一个这样的数组:
const array = [
{ id: 1, name: 'a1', props: [
{ name: 'b1', typeId: 1 },
{ name: 'b2', typeId: 1 },
{ name: 'b3', typeId: 5 },
{ name: 'b4', typeId: 5 },
] },
{ id: 2, name: 'a2', props: [
{ name: 'c1', typeId: 1 },
{ name: 'c2', typeId: 1 },
{ name: 'c3', typeId: 5 },
] },
{ id: 3, name: 'a3', props: [
{ name: 'd1', typeId: 5 },
{ name: 'd2', typeId: 5 },
] },
{ id: 4, name: 'a4', props: [
{ name: 'e1', typeId: 1 },
] }
];
我想通过 prop 的 typeId 属性过滤这个数组。例如:
如果typeId == 5
,那么它应该返回 id 为 1、2、3 且只有 props 的 typeId 等于 5 的项目。像这样:
filteredArray = [
{ id: 1, name: 'a1', props: [
{ name: 'b3', typeId: 5 },
{ name: 'b4', typeId: 5 },
] },
{ id: 2, name: 'a2', props: [
{ name: 'c3', typeId: 5 },
] },
{ id: 3, name: 'a3', props: [
{ name: 'd1', typeId: 5 },
{ name: 'd2', typeId: 5 },
] }
];
或者如果typeId == 1
,那么它应该返回 id 为 1、2、4 的项目,只有 typeId 等于 1 的道具。像这样:
filteredArray = [
{ id: 1, name: 'a1', props: [
{ name: 'b1', typeId: 1 },
{ name: 'b2', typeId: 1 },
] },
{ id: 2, name: 'a2', props: [
{ name: 'c1', typeId: 1 },
{ name: 'c2', typeId: 1 },
] },
{ id: 4, name: 'a4', props: [
{ name: 'e1', typeId: 1 },
] }
];
我写了这样的东西,但它没有按预期工作。它不过滤道具数组。如果它的 props 数组有一个 typeId 等于 的项目,则返回一个项目typeId
。
let typeId = 1;
let filteredArray = array.filter(x => {
return x.props.some(y => {
return y.typeId == typeId;
});
});
如果您不介意修改输入数据,可以使用forEach
:
array.forEach(
(elt) => elt.props = elt.props.filter((subElt) => subElt.typeId === 5)
)
此外,您可能想要过滤具有elt.props
空的元素:
const result = array.filter(elt => elt.props.length > 0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句