1

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 .

3 Answers 3

2

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

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

Comments

0
new Function(`return ${element}`)()

1 Comment

sorry I have done typo...its really working..thank you @guest271314
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.