I have a object, need to parse the below data
var data= [{"obj1":"2122"},{"obj2":"123"}]
to get both the keys and values in javascript. I yried to use:
var obj = JSON.parse(data);
for(var prop in data) {
if(data.hasOwnProperty(prop))
console.log(prop);
}
The values that are obtained in console are
Object {obj1: "2122"}
Object {obj2: "123"}
But I need to access the values seperately and not as object. How to retrieve it from that object?
JSON.parse is use to parse JSONString to Javascript Object.
You can not use it directly on a JavaScript Object ...
Anyway, your object is an array so you may do :
var arr = JSON.parse(data);
arr.forEach(function(elementObject){
var keys = Object.keys(elementObject);
keys.forEach(function(key){
console.log(key + ":"+elementObject[key]);
})
});
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With