Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse json object in javascript to get key and values

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?

like image 543
Rajeshwar Avatar asked Jul 25 '26 06:07

Rajeshwar


1 Answers

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

like image 93
mimiz Avatar answered Jul 27 '26 19:07

mimiz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!