簡體   English   中英

Javascript對象數組:返回值的最佳方法?

[英]Javascript array of objects: Best way to return a value?

我有一個Javascript對象數組,帶有兩個具有此結構的鍵:

"data": [
  {
  "description": "Unknown",
  "type": 0
  },
  {
  "description": "On",
  "type": 1
  },
  {
  "description": "Off",
  "type": 2
  },
  ...
  ]

我想給它傳遞一個“類型”的數值,如果它在數組中找到它,就向我返回描述值。 例如,如果我傳遞“ 0”,我希望它返回“未知”。

這可以通過for或forEach循環輕松完成,但是JS中有一個內置函數可以讓我在一行中完成它?

您可以使用任一find

 var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }]; console.log(data.find(({ type }) => type === 1).description); 

或為快速訪問而對類型使用哈希表

 var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }], types = Object.assign(...data.map(({ type, description }) => ({ [type]: description }))); console.log(types[1]); 

Map

 var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }], types = data.reduce((m, { type, description }) => m.set(type, description), new Map); console.log(types.get(1)); 

在一個襯里中,您可以過濾列表。

 var obj=[{ "description": "Unknown", "type": 0 }, { "description": "On", "type": 1 }, { "description": "Off", "type": 2 }]; var filterType=1; console.log(obj.filter(e=>e.type == filterType)[0]['description']) 

查看附帶的代碼段,它給出了所需的輸出。

  • 查找函數遍歷整個數組以匹配條件,例如,在這種情況下,passedIndex將檢查它是否存在於列表中

  • 如果存在,請退回該物品

 var list = [{ "description": "Unknown", "type": 0 }, { "description": "On", "type": 1 }, { "description": "Off", "type": 2 } ]; function findItem(index) { var result = list.find(function(item) { if (item.type == index) { return item; } }); return result.description; } var description = findItem(2); console.log('The Description is "' + description + '"') 

暫無
暫無

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

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