简体   繁体   English

如何过滤 Javascript 中的嵌套对象

[英]How to filter nested objects in Javascript

How would I use the filter() on nested items?我将如何在嵌套项目上使用 filter() ? I am trying to retrieve all the data that has a projex.HeightPay === '1'.我正在尝试检索具有 projex.HeightPay === '1' 的所有数据。 I would like to get back the Id, Name,System etc and the projex items if the HeightPay is 1.如果 HeightPay 为 1,我想取回 Id、Name、System 等和项目项目。

For example:例如:

  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");

Desired output:所需的 output:

  {
    Id: "022173333101",
    Name: "Blue",
    System: "DESIGN",
    Squares: 0,
    Attributes: {
      projex: [
        {
          Project: "50",
          HeightPay: "1"
        }
      ]
    },
    Customer: {
      Addr1: "Somewhere",
      Addr2: ""
    }
  }

You can use Array.prototype.map to go through each element of the fakeData array and then filter on the child array Attributes.projex using Array.prototype.filter and return a new object from the map call for every iteration You can use Array.prototype.map to go through each element of the fakeData array and then filter on the child array Attributes.projex using Array.prototype.filter and return a new object from the map call for every iteration

The new object in the Array.prototype.map call is formed by taking all the properties of each element of fakeData using the object spread operator ... except the Attributes.projex property and then assigning the new Attributes.projex array from the Array.prototype.filter to each new object: Array.prototype.map调用中的object 是通过使用 object 扩展数组运算符fakeData的每个元素的所有Attributes.projex ,然后分配Attributes.projex Array.prototype.filter运算符... Array.prototype.filter到每个新的 object:

 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);

const result = fakeData.map(item => ({ ...item, Attributes: { projex: item.Attributes.projex.filter(e => e.HeightPay === "1") } }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM