json数据:
var fruit = [{"apple":1000},
{"mango":100},{"orange":200}];
var user_input = "apple"; //this will change dynamically.
for(var key in fruit) {
var val = fruit[key];
console.log(val[user_input]);
}
output: undefined
我想使用用户输入来访问数据
答案 0 :(得分:1)
您必须遍历fruit
数组以找到具有密钥的对象。
var fruit = [{"apple":1000},{"mango":100},{"orange":200}];
var user_input = "apple";
const obj = fruit.find((obj) => Object.keys(obj).includes(user_input));
if (obj) console.log(obj[user_input]);