[英]Javascript array of objects: Best way to return a value?
I have an array of objects in Javascript with two keys with this structure: 我有一个Javascript对象数组,带有两个具有此结构的键:
"data": [
{
"description": "Unknown",
"type": 0
},
{
"description": "On",
"type": 1
},
{
"description": "Off",
"type": 2
},
...
]
I want to pass it a 'type' numeric value and if it finds it in the array, returns me the description value. 我想给它传递一个“类型”的数值,如果它在数组中找到它,就向我返回描述值。 For example, if I pass '0', I want it to return 'Unknown'.
例如,如果我传递“ 0”,我希望它返回“未知”。
This is easily done with a for or forEach loop, but there is an inbuilt function in JS that lets me do it in a single line? 这可以通过for或forEach循环轻松完成,但是JS中有一个内置函数可以让我在一行中完成它?
You could use either find
您可以使用任一
find
var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }]; console.log(data.find(({ type }) => type === 1).description);
or for faster access use a hash table for the types 或为快速访问而对类型使用哈希表
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]);
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));
Have a look at the attached code snippet , which gives the desired output. 查看附带的代码段,它给出了所需的输出。
Find function to itreat throughout your array to match the condition ie in this case the passedIndex to check whether it is present in list 查找函数遍历整个数组以匹配条件,例如,在这种情况下,passedIndex将检查它是否存在于列表中
If present return the item 如果存在,请退回该物品
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.