access value from dynamic json array in javascript

Advertisements

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"?

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

Leave a Reply Cancel reply