0

json Data:

 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

i want to access the data using user input

1 Answer 1

1

You'll have to iterate through the fruit array to find the object that has the key.

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]);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.