如何在嵌套项目上使用 filter() ?我正在尝试检索具有 projex.HeightPay === '1' 的所有数据。如果 HeightPay 为 1,我想取回 Id、名称、系统等和项目项目。
例如:
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
数组的每个元素,然后对子数组Attributes.projex
进行过滤> 使用 Array.prototype.filter
并从每次迭代的 map
调用中返回一个新对象
Array.prototype.map 调用中的new对象是通过获取fakeData每个元素的所有属性而形成的
使用对象扩展运算符 ...
(除了 Attributes.projex
属性),然后从Array.prototype.filter
到每个新对象:
const fakeData = [ { Id: "022173333101", Name: "Blue", System: "DESIGN", Squares: 0, Attributes: { projex: [ { Project: "50", HeightPay: "1" }, { Project: "50", HeightPay: "0" } ] }, Customer: { Addr1: "Somewhere", Addr2: "" } } ];
const found = fakeData.map(data => ({
...data,
Attributes: {
projex: data.Attributes.projex.filter(({
HeightPay
}) => HeightPay === "1")
}
}));
console.log(found);
关于javascript - 如何在 Javascript 中过滤嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61067186/