1

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

  • What's the object name? Take a look at [for in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) – NiCk Newman May 18 '15 at 06:34
  • You **do not** have a "JSON object". You have a **Javascript object (literal)** -- or you have a "JSON **string**". In the example you show it is the former. If you really wanted to work with JSON you would have to use string functions. Because anything JSON is **a string**. But you can convert a JSON representation into an object in whatever language -- here Javascript -- you are using. One: a programming language. Two (JSON): a string format for data exchange and storage, independent of programming languages. – Mörre May 18 '15 at 06:39

3 Answers3

1

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);
}
Maarten Peels
  • 1,002
  • 1
  • 13
  • 29
1

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]); }
Kutyel
  • 8,575
  • 3
  • 30
  • 61
  • I tried your answer to some success the courses array is okay I cant seem to get the scores for each class in the values array. have a look http://plnkr.co/edit/RXzjPllg0RSWjvgMjIoU?p=preview – Anthony Akpan May 18 '15 at 14:47
  • @AnthonyAkpan glad to help ^_^ – Kutyel May 18 '15 at 15:39
0

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;

undefined
  • 191
  • 1
  • 8