Skip to main content

Getting key/value pair from JSON object and getting variable name and value from JavaScript object.

 Hi, I had faced one issue like this. I have an JSON object but I don't know any key name but I need to get the all the key and corresponding value from JSON object using client side JavaScript. Suddenly I wondered whether it's possible or not, after that I had done lot of workaround and finally got this solution. See the below example.
  function getKeyValueFromJSON() {
    var jsonObj = {a:10,b:20,c:30,d:50};
    for(var key in jsonObj) {
      alert("Key: " + key + " value: " + jsonObj[key]);

 In this example I have created the one json array as string, and converted this string into JSON object using eval() function. Using for-each loop I got all the key value from jsonObj, and finally using that key I got the corresponding value.
 Finally I got the alert like this,

   Key: a value:10
   Key: b value:20
   Key: c value:30
   Key: d value:50

 During this workaround I got one more idea, using this same way I got all the variable name and corresponding value from JavaScript object. See the below example.
 This is my JavaScript class. Here I have declared a function for variable d.
   function testJavaScriptClass() {
    this.a = 10;
    this.b = 20;
    this.c = 30;
    this.d= function() {
               return "Test result from inside this function";

 Now I am going to create one object for this class and going to get the variable name and corresponding value from JavaScript object.

 function getKeyValueFromJSObject() {
    var testObj = new testJavaScriptClass();
    for(var key in testObj) {
      if(typeof testObj[key] != "function") {
            alert("Key: " + key + " value: " + testObj[key]);   
      else {
            var value = testObj[key]();
            alert("Key: " + key + " value: " + value);

 Here I have checked the key (variable) is whether a function or not. If it is function then, I executed the function and get the result.
 Finally I got the alert this.

  Key: a value:10
  Key: b value:20
  Key: c value:30
  Key: d value: "Test result from inside this function"

Hope this help...!


Shamshul said…
I want to get it from mongodb console
to find the field name of the second record
Unknown said…
What if I have nested JSON like the below:

Gnanasuriyan said…
@Krishnamachari Shrikanth : For your input, we need to have recursive function.
Anonymous said…
It doesn't look like a javascript Object at all. you are simply using an array and looping thru the array.

Try looping thru this Object

var myObj = {id:1, name="joe", age=31", isAGenius=true}
Please help me on this..

JSON Response:

"Result1": {
"abc": 1,
"def": 2
"Result2": {
"abc": 3,
"def": 4

I need to know the following
1) length of CompleteResult
2) how to get the value "Result1" i.e, I may have Result3 in next response, I dont know what value will be coming there. So I have to get the value dynamically
Anonymous said…
Thank you!!! So simple, so elegant. You saved lot of my time.

Hi can u tell me how can access and take nested json key and values
Hi I have lot of json object in fouser table .For particular object say id is ObjectId("533a91b2263e03670b000009") taking means no problem working.I mean see the below map reduce concept in if condition[docid == ObjectId("533a91b2263e03670b000009")] hot coded.So working.

'collectionName' : 'fouser',
mapReduce : {
map : 'function () {
var docid = this._id.valueOf();

var date =;
var doc = this,
rec = doc.records;
if( docid == ObjectId("533a91b2263e03670b000009") ){
var i = 0;
Object.keys(rec).forEach(function(key) {

emit (NumberInt(i), { recordid : ObjectId(key) , completed : rec[key].completed, datedue:rec[key].due});
i = i+1;

reduce : 'function (key, values) {
var allDetails = [];
var user = { recordid: null, completed : null};
for( var index = 0; index < values.length; index++){
user.recordid = values[index].recordid;
user.completed = values[index].completed;
user = { recordid : null, completed : null};
return {list : allDetails}
out : 'list',



Instand of hot coding i passing dyanamically means showing error like "object.keys called on non object in object.keys Object.keys(rec).forEach(key) ".How can i resolve please help me .I'm using this inside jaspersoft
It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.

Selenium Training in Chennai

Selenium Training in Bangalore
It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.

Selenium Training in Chennai

Selenium Training in Bangalore
Unknown said…
Appreciation for really being thoughtful and also for deciding on certain marvelous guides most people really want to be aware of.

AWS Training in Chennai
Vicky Ram said…
Great blog!!! It was very impressed to me. I like so much and keep sharing. Thank you.

This comment has been removed by the author.
rocky said…
I hope it’s useful to many individuals for whose looking this precious information to developing their skill. I am so proud of you and your efforts and work make me realize that anything can be done with patience and sincerity.
python training in chennai

python online training in chennai

python training in bangalore

python training in hyderabad

python online training

python flask training

python flask online training

python training in coimbatore

Unknown said…
Cognex offer AWS Training and certification in Chennai. And also cognex offers various courses according to the students requirements.
Anonymous said…
Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post
data analytics in hyderabad
Sarthak Yadav said…
Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts likethis.
Prwatech said…
This information is impressive..I am inspired with your post writing style & how continuously you describe this topic.

Best Data Science Training Institute in Pune
best data science training institute in bangalore
Technogeekscs said…
Thanks for Sharing a Very Informative Post & I read Your Article & I must say that is very helpful post for us.
Best RPA Training in Pune
AWS Training in Pune
Unow22 said…
com/wp-content/uploads/2021/06/Screen-Shot-2021-06-18-at-11.04.13-AM-1024x681.png 1024w, https://www. Still have questions about that (faux) pee smell? We have answers. Why do some people fail a test even after using synthetic pee? The most common reasons are that people don’t mix the urine properly, or that the specimen is not heated to a realistic 98. Visit:
ppc fame said…
This Digital Marketing Course in Mohali transforms you into a complete Digital Marketer with expertise in modules like SEO, Social Media Marketing, PPC, Analytics, Content, Mobile, and Email marketing.
We provide the Best training for Social Media Marketing and PPC course in Mohali and have trained over 10k students.
Become industry-ready learning the latest tools, working on real-world projects, and attending Masterclasses from the Google and Facebook certified Team.
Digital Marketing Course in Chandigarh
ppc fame said…
This Digital Marketing Course in Panchkula transforms you into a complete Digital Marketer with expertise in modules like SEO, Social Media Marketing, PPC, Analytics, Content, Mobile, and Email marketing.
Digital Marketing institute in Panchkula
Anonymous said…

Launch your NFT Marketplace and attract millions of NFT enthusiasts and artists to put their NFTs on display with our White Label NFT Platform. With over 5+ years of experience in Whitelabel NFT Marketplace Development, we help you develop a customizable platform that enables easy and secure NFT trading. Hence, our White Label NFT Marketplace Development Company guarantees to provide you with a platform through which creators can easily transfer their assets into NFTs, collect and transfer them without any arbitrators in absolute transparency.

White label nft marketplace
White label nft marketplace development
Mahesh123 said…
its good article it is very helfull for me
Azure Data Factory course in Ameerpet,Azure Data Engineer Training Online Hyderabad,azure training in hyderabad ameerpet,Azure Data Factory online Training in Hyde
Himani said…
Up-to-date information with all relevant points.

Best Digital Marketing Institutes in India

Punith said…
I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows the efforts on research and your understanding on this subject. Bookmarked this page, will come back for more.. Data Analytics courses in germany
mcsterling said…
such good knowledge that's you sharing, kindly visit our website page
amina said…
Hey, it was a well built and well written article from your side, I am bookmarking this for reading again as it is quite insightful. kindly, keep posting articles on this topic. Best Data analytics Courses in India
kamal said…
Well written, excellent article. Very informative thanks for sharing this informative article. Digital Marketing Courses In Tembisa
Babu said…
Very well written and brilliant article. Pretty interesting to read. I really enjoy reading this article. You have produced a brilliant article. Digital Marketing Courses In Doha
sachin said…
Looking for a Second Hand Laptop In Gurgaon? Look no further! We offer a wide selection of pre-owned laptops at affordable prices. All of our laptops are thoroughly tested and come with a warranty for your peace of mind. Shop with us today and upgrade your tech game without breaking the bank.
Seoprac said…
Very good article. Gives you information on MVC and how to use it.
Digital Marketing Courses In hobart

Popular posts from this blog

Ext JS 4 – Creating web page using Ext.container.Viewport class and region propery

The Ext.container.Viewport is used for creating general web page and region property is used for splitting web page into different parts. Ext.container.Viewport is a specialized container represents the viewable area of the application (the browser area). It render itself to the document body, there is no need for providing renderTo property and it automatically sizes itself to size of the browser viewport. The viewport also re-size the child elements based on view area(based on browser width and height). The default layout of the viewport is border layout and we can customize this property according to our requirements. The viewport does not provide any scrolling. If necessary, the child elements(generally panels) within viewport needs to provide a scroll feature by using autoScroll property. See the below example for better understanding. This is Home.js file placed into app/view folder. Ext.define('MyApp.view.Home', { extend : 'Ext.container.Viewport&#

Getting servlet init parameter that is defined in web.xml

1. Create a new dynamic web project using eclipse. 2. Create a one new servlet and include the following code. package com.controller ; import; import javax.servlet .ServletConfig; import javax.servlet .ServletException; import javax.servlet .annotation.WebServlet; import javax.servlet .http.HttpServlet; import javax.servlet .http.HttpServletRequest; import javax.servlet .http.HttpServletResponse; @ WebServlet ( "/LoginController" ) public class LoginController extends HttpServlet {                 private static final long serialVersionUID = 1L;                 public LoginController() {         super ();     }     protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {                                 ServletConfig config = getServletConfig ();                                 System.out.println( "Init parameter user nam

Simple Login Application Using Spring MVC and Hibernate – Part 1

 I hope developers working in web application development might hear about MVC architecture. Almost all technologies provide support for MVC based web application development, but the success is based on many factors like reusable of the code, maintenance of the code, future adaption of the code, etc..,  The success of the Spring MVC is “ Open for extension and closed for modification ” principle. Using Spring MVC the developers can easily develop MVC based web application. We don’t need any steep learning curve at the same time we need to know the basics of spring framework and MVC architecture. The Spring MVC consists of following important components. 1. Dispatcher servlet 2. Controller 3. View Resolver 4. Model Spring MVC - Overview  The overall architecture of Spring MVC is shown here.  1. When “Dispatcher Servlet” gets any request from client, it finds the corresponding mapped controller for the request and just dispatches the request to the corresponding contro