簡體   English   中英

如何過濾 Javascript 中的嵌套對象

[英]How to filter nested objects in Javascript

我將如何在嵌套項目上使用 filter() ? 我正在嘗試檢索具有 projex.HeightPay === '1' 的所有數據。 如果 HeightPay 為 1,我想取回 Id、Name、System 等和項目項目。

例如:

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

所需的 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

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