I have json object as following
var data = {
datetime:{
time:"9:30 AM",
date:"24-09-2017"
}
}
and i have string var element = "data.datetime.time"
how to access the time using element .
Split the string (dot as separator), and use Array#reduce to extract the data from the object:
var data = { datetime:{ time:"9:30 AM", date:"24-09-2017" } } var element = "data.datetime.time"; var result = element.split('.').reduce(function(r, p) { return typeof r === 'object' ? r[p] : null; // if r is an object, return the prop value, if not return null }, { data: data }); console.log(result);
new Function(`return ${element}`)()
I have just found the answer for this..
simply we can use eval()
var data = {
datetime:{
time:"9:30 AM",
date:"24-09-2017"
}
}
var element = "data.datetime.time";
console.log(eval(element));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.