如何在Javascript中过滤嵌套对象
如何在嵌套项上使用filter()?我正在尝试检索所有具有projex.HeightPay==“1”的数据。如果HeightPay为1,我想取回Id、名称、系统等和项目 例如:如何在Javascript中过滤嵌套对象,javascript,Javascript,如何在嵌套项上使用filter()?我正在尝试检索所有具有projex.HeightPay==“1”的数据。如果HeightPay为1,我想取回Id、名称、系统等和项目 例如: const fakeData = [ { Id: "022173333101", Name: "Blue", System: "DESIGN", Squares: 0, Attributes: { projex: [ { Pr
const fakeData = [
{
Id: "022173333101",
Name: "Blue",
System: "DESIGN",
Squares: 0,
Attributes: {
projex: [
{
Project: "50",
HeightPay: "1"
},
{
Project: "50",
HeightPay: "0"
}
]
},
Customer: {
Addr1: "Somewhere",
Addr2: ""
}
}
];
// returns nothing
const found = fakeData.filter(data => data.Attributes.projex.HeightPay === "1");
期望输出:
{
Id: "022173333101",
Name: "Blue",
System: "DESIGN",
Squares: 0,
Attributes: {
projex: [
{
Project: "50",
HeightPay: "1"
}
]
},
Customer: {
Addr1: "Somewhere",
Addr2: ""
}
}
您可以使用
Array.prototype.map
遍历fakeData
数组的每个元素,然后使用Array.prototype.filter
对子数组属性进行过滤。projex
使用Array.prototype.filter
从map
调用为每次迭代返回一个新对象
Array.prototype.map
调用中的新对象是通过使用对象扩展操作符…
获取fakeData
中每个元素的所有属性(除了Attributes.projex
属性),然后从Array.prototype.filter
到每个新对象:
const fakeData=[{Id:“02217333101”,名称:“蓝色”,系统:“设计”,方块:0,属性:{projex:[{Project:“50”,HeightPay:“1”},{Project:“50”,HeightPay:“0”}],客户:{Addr1:“某处”,Addr2:“}];
const found=fakeData.map(数据=>({
…数据,
属性:{
projex:data.Attributes.projex.filter(({
高薪
})=>高薪===“1”)
}
}));
console.log(找到)代码>const result=fakeData.map(项=>({
…项目,
属性:{
projex:item.Attributes.projex.filter(e=>e.HeightPay==“1”)
}
}))