Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Javascript中过滤嵌套对象_Javascript - Fatal编程技术网

如何在Javascript中过滤嵌套对象

如何在Javascript中过滤嵌套对象,javascript,Javascript,如何在嵌套项上使用filter()?我正在尝试检索所有具有projex.HeightPay==“1”的数据。如果HeightPay为1,我想取回Id、名称、系统等和项目 例如: const fakeData = [ { Id: "022173333101", Name: "Blue", System: "DESIGN", Squares: 0, Attributes: { projex: [ { Pr

如何在嵌套项上使用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
数组的每个元素,然后使用
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”)
}
}))