【问题标题】:Check the variable's value is the Javascript object array's key and return that key's value [closed]检查变量的值是Javascript对象数组的键并返回该键的值[关闭]
【发布时间】:2019-02-04 05:30:18
【问题描述】:
array = {
event: [{
key: "value",
lbl: "value"
}],
event1: [{
key: "value",
lbl: "value"
}]
var variable;
if(variable in array){
//what to do here?
}
我在变量中有一个值,它将是数组中的数组名称(即):variable="event" 或 "event1";
我想要一个函数用变量中的键返回数组!
【问题讨论】:
标签:
javascript
arrays
json
【解决方案1】:
如果你想使用变量访问任何属性,你需要使用[] Bracket notation 来访问对象
let arr = {event: [{key: "value",lbl: "value"}],event1: [{key: "value",lbl: "value"}]}
var variable = 'event1'
console.log(arr[variable])
【解决方案2】:
您的 array 变量不是数组,而是对象。您可以使用括号表示法访问对象的属性/值(即:event 和 event1):
arr["event1"] // returns the array (the key's value) at event one.
因此,您可以使用以下箭头函数从任何给定的key 获取任何给定的object 的值:
getVal = (obj, key) => obj[key];
虽然功能不是必需的,但我已根据您的要求创建了一个。或者,您可以使用:
obj[varaible] // returns the array (value) from the key (variable)
请参阅下面的工作示例:
const obj = {
event: [{
key: "value",
lbl: "value"
}],
event1: [{
key: "value",
lbl: "value"
}]
},
getVal = (obj, key) => obj[key],
variable = "event";
console.log(getVal(obj, variable));
【解决方案3】:
使用括号表示法从对象中访问键
array = {
event: [{
key: "value",
lbl: "value"
}],
event1: [{
key: "value",
lbl: "value"
}]
}
var variable='event1';
console.log(variable, array[variable])