簡體   English   中英

如何在我的 Angular 應用程序中的數組中從 Object 中獲取價值

[英]How To Get Value From An Object Inside An Array In My Angular Application

所以我在我的 Angular 應用程序中有來自 API 的 object 數組

"register":[
{
"club": 8,
"players": 100,
"officials": 10
},
{
"male": 7,
"female": 2,
"other": 1
},
{
"Brazil": 5,
"France": 1,
"Italy": 2,
"England": 2
}
]

我的目標是在控制台的第三個 object 中顯示一個項目。 所以我嘗試以這種方式循環遍歷 object 的數組:

 let country =  data['register'].map(data => data.England)
  console.log(country) // Output: [undefined, undefined, 2]

我猜未定義來自前兩個對象。

如何循環遍歷此 object 以僅在第三個 Object 中獲得英格蘭的數字,而前兩個未定義顯示?

注意

數據來自我在.ts文件中訂閱的 API。 它包含來自 API 的所有結果。

你可以.filter()出所有沒有England鍵的對象(並保留所有那些),然后.map()你的對象數組,如下所示:

 const data = {register:[{club:8,players:100,officials:10},{male:7,female:2,other:1},{Brazil:5,France:1,Italy:2,England:2}]}; let country = data.register.filter(obj => 'England' in obj) // keep all objects in your array with the England property.map(obj => obj.England) // map to the england property console.log(country) // Output: [2]

如果England的值永遠不能為0 ,則可以在映射后使用Boolean()進行.filter() ,如下所示:

 const data = {register:[{club:8,players:100,officials:10},{male:7,female:2,other:1},{Brazil:5,France:1,Italy:2,England:2}]}; const country = data.register.map(({England}) => England).filter(Boolean); console.log(country) // Output: [2]


編輯:根據您在評論中的問題,如果您希望將每個屬性的數值放入數組中,您可以使用.flatMapObject.values()

 const data = {register:[{club:8,players:100,officials:10},{male:7,female:2,other:1},{Brazil:5,France:1,Italy:2,England:2}]}; let country = data.register.filter(obj => 'England' in obj) // keep all objects in your array with the England property.flatMap(Object.values) // flatMap the array returned by Object.values console.log(country) // Output: [5, 1, 2, 2]

或者使用 lodash(兼容更多瀏覽器):

 const data = {register:[{club:8,players:100,officials:10},{male:7,female:2,other:1},{Brazil:5,France:1,Italy:2,England:2}]}; const englandObjects = _.filter(data.register, obj => 'England' in obj) const numberVals = _.flatMap(englandObjects, Object.values); console.log(numberVals);
 <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

您可以使用_.compact(array)內置 function 刪除所有虛假值,如 false、null、0、“”、未定義和 NaN。

let country = _.compact(data['register'].map(data => data.England));
console.log(country) // Output: [2]

map 的用例與您想要實現的完全不同。 Map 迭代您的 collections 並為 collections 下的每個項目生成新結果並將返回該結果。 因此,對於前兩個 object 它沒有找到Undefined 您有 3 個 object,您有 3 個數組,前兩個未定義當您想要處理 collections 並想要具有所需結果的新集合時使用 map。

在這里您可以使用查找:

const foundItem = data.register.find(item => item.England)
console.log(foundItem.England); // you can access all attributes here
console.log( [foundItem.England] ); // as array

暫無
暫無

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

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