亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Javascript 中過濾嵌套對象

如何在 Javascript 中過濾嵌套對象

九州編程 2022-06-16 16:32:01
我將如何在嵌套項目上使用 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 nothingconst 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: ""    }  }
查看完整描述

2 回答

?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

您可以使用Array.prototype.map遍歷數組的每個元素,然后使用fakeData過濾子數組并從每次迭代的調用中返回一個新對象Attributes.projexArray.prototype.filtermap


調用中的新對象Array.prototype.map是通過使用對象擴展運算符獲取每個元素的所有屬性(屬性除外) ,然后將新數組從分配給每個新對象:fakeData...Attributes.projexAttributes.projexArray.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);


查看完整回答
反對 回復 2022-06-16
?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

const result = fakeData.map(item => ({

        ...item,

        Attributes: {

                projex: item.Attributes.projex.filter(e => e.HeightPay === "1")

        }

}))


查看完整回答
反對 回復 2022-06-16
  • 2 回答
  • 0 關注
  • 275 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號