簡體   English   中英

如何在 angular 中獲取 API 的響應數據中迭代對象數組?

[英]How to iterate over an array of objects in response data of a get API in angular?

假設我在 angular 中有一個 GET API 的響應主體,它的對象數組如下所示:

79: {customerId: '61c1b85fa7b16079fe7b5b64', title: 'Mr', phoneNumber: Array(0), jobProfile: 'GOLD', designation: 'Uuuuuuuuuuuu', …}
80: {customerId: '61c1b904a7b16079fe7b5b65', title: 'Mr', phoneNumber: Array(0), jobProfile: 'DIAMOND', designation: 'Player', …}
81: {customerId: '61c1b94aa7b16079fe7b5b66', title: 'Mr', phoneNumber: Array(0), jobProfile: 'DIAMOND', designation: 'Boss', …}
82: {customerId: '61c1b987a7b16079fe7b5b67', title: 'Mr', phoneNumber: Array(0), jobProfile: 'DIAMOND', designation: 'Vvvjkb ', …}
83: {customerId: '61c1bb4ca7b16079fe7b5b68', title: 'Mr', phoneNumber: Array(0), jobProfile: 'DIAMOND', designation: 'Player', …}
84: {customerId: '61c1bbd3a7b16079fe7b5b69', title: 'Mrs', phoneNumber: Array(0), jobProfile: 'GOLD', designation: 'Player', …}
85: {customerId: '61c1bd0ca7b16079fe7b5b6a', title: 'Mr', phoneNumber: Array(0), jobProfile: 'GOLD', designation: 'Player', …}
86: {customerId: '61c1bd4ba7b16079fe7b5b6b', title: 'Mr', phoneNumber: Array(0), jobProfile: 'DIAMOND', designation: 'CEO', …}
87: {customerId: '61c1bf34a7b16079fe7b5b6c', title: 'Mr', phoneNumber: Array(0), jobProfile: 'GOLD', designation: 'HELLO', …}
88: {customerId: '61c1bf79a7b16079fe7b5b6d', title: 'Mrs', phoneNumber: Array(0), jobProfile: 'DIAMOND', designation: 'Vvvvvvvvvv', …}
89: {customerId: '61c1c2b2a7b16079fe7b5b6e', title: 'Mr', phoneNumber: Array(0), jobProfile: 'DIAMOND', designation: 'Hiiii', …}
90: {customerId: '61c1c8c7a7b16079fe7b5b6f', title: 'Mr', phoneNumber: Array(0), jobProfile: 'GOLD', designation: 'CEO', …}

這是一個數組,它有 1000 個條目,所以如果我想遍歷這個響應主體並且我想匹配一個特定的 customerId,以便我可以將 customerId 保存在本地存儲中,然后獲取特定行的詳細信息。 我怎么能在 angular 中做到這一點?

這是 angular 中非常基本的事情。

要在 API 響應中查找特定 ID,只需將響應保存在變量中(如果以后使用),或在 API 響應中創建局部變量,然后您可以提取包含 ID 的 object。

這是一個示例代碼:

this.httpService.get('API_CAll_ROUTE_').subscribe(
   response => {
      const specificCustomer= response.find(el => el.customerId=== '61c1b85fa7b16079fe7b5b64');
      if (specificCustomer) {
         localStorage.set('customer', JSON.stringify(specificCustomer.customerId));
      }
   }
);

當你從 localStorage 獲取它時,你可以簡單地調用 JSON.parse 來獲取 object。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM