通過數組filter方法過濾數組中對象


通過過濾器filter獲取數組對象的屬性名和屬性值

 const arr = [
        {
          label: '張三',
          value: '111111',
        },
        {
          label: '李四',
          value: '22222',
        },
      ]
      //通過filter過濾獲取到新數組
      //第一種寫法:
      //   const newArr = arr.filter((item) => {
      //     if (item.label === '張三') {
      //       return item
      //     }
      //   })
       //第二種寫法:
    //   const newArr = arr.filter((item) => {
    //     return item.label === '張三'
    //   })
       //第三種寫法:(推薦)
       const newArr = arr.filter(item=>item.label === '張三')

      console.log(newArr) //返回獲取到label值為張三的一個對象數組(過濾后的新數組)
      const value = newArr[0].value//數組索引0代表過濾后的新數組中第一個對象,切記當過濾后的新數組有多個對象時根據自己需要指定對應的索引
      console.log(value) //返回獲取到數組中label值為張三對象的value值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM