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}`)()