Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

access value from dynamic json array in javascript

I have a result from an api call

var result = [
    {
        "m1": "State"
    },
    {
        "m2": "Occupation"
    },
    {
        "m3": "Qualification"
    },
    {
        "m4": "Salary"
    },
    {
        "m5": "Age"
    },
    {
        "m6": "Status"
    }
]

I want to be able to grab each value with $.each loop but can’t seem to figure it out.
Here is my code so far.

var meta = $.parseJSON(result)
$.each(meta, function(index, value){
    console.log(value)
})

The question is how can I log these values "State" and "Occupation", "Qualification", "Salary", "Age" and "Status"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know one can’t do value."m"+index+1

Please point me the right way.

>Solution :

If you are using js then it will be very easy to iterate values

var result = [
    {
        "m1": "State"
    },
    {
        "m2": "Occupation"
    },
    {
        "m3": "Qualification"
    },
    {
        "m4": "Salary"
    },
    {
        "m5": "Age"
    },
    {
        "m6": "Status"
    }
];

for(var i=0;i<result.length;i++){
//get the key of the object  
var key=Object.keys(result[i])[0];
//get the value of an object
var value=result[i][key];
console.log(value);
}
//jquery
$.each(result,function(index,obj){
var key=Object.keys(obj)[0];
var value=obj[key];
console.log(value)

})




 //dynamic function to iterate array
        function iterateArray(array){
         $.each(array, function(index, obj) {
            $.each(obj, function(key, value) {
              console.log(value);
            });
          });
        }

I hope this will be helpful you just need to pass array to this function

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading