Anthony Akpan
Anthony Akpan

Reputation: 73

Return JSON Name and values in seperate arrays

if I have the following JSON object

{ 
    "ID": 100, 
    "Name": "Sharon", 
    "Classes":{
                "Mathematics": 4, 
                "English": 85, 
                "Chemistry": 70, 
                "Physics": 4, 
                "Biology": 8, 
                "FMathematics": 94 
              }
  }

how can I return the Class names and their respective values in separate arrays?

here the plunker http://plnkr.co/edit/RXzjPllg0RSWjvgMjIoU?p=preview

Upvotes: 1

Views: 499

Answers (3)

Kutyel
Kutyel

Reputation: 9084

You can use native js code to do this, no tricks:

var keys = [], values = [];
for (var key in json){ keys.push(key); values.push(json[key]); }

Upvotes: 1

Maarten Peels
Maarten Peels

Reputation: 1022

This will return a object with all the arrays inside.

var obj = JSON.Parse("Your json string");
var arrays = [];

for(var className in  obj.Classes){
    var value = obj.Classes[className];//Value of className
    var temp = {};
    temp[className] = value;
    arrays.push(temp);
}

Upvotes: 1

undefined
undefined

Reputation: 191

if you use jquery, you can do this:

var keys = []
var values = []
$.each(yourJSONObject.Classes, function(k, v){keys.push(k); values.push(v)})

then you can get the keys and values seperated;

Upvotes: 0

Related Questions