0

My JSON data has following format :

[{"Name":"A","Id":"1"},{"Name":"B","Id":"2"},{"Name":"C","Id":"3"}]

How covert this into two separate arrays as Name[] and Id[] using JavaScript ? I need the data in the following manner:

Name[0] should be : "A"
Name[1] should be : "B" and so on ... 
0

3 Answers 3

1

this should work, jsonArray is your JSON

var name = [], ids = [];
jsonArray.forEach(function(item){
  name.push(item.Name);
  ids.push(item.Id);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Its not working for me.. The JSON data which I want to covert to arrays is actually in the xmlHttp.responseText (since m getting it from a web service)..
You wrote that your jsonData is in this format. so whats the format of your jsonData? if it is wrapped in xhr.resposneText you need to parse it as JSON or provide the code.
this is my script code : var Url = "some url"; var xmlHttp = null; xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", Url, false ); xmlHttp.send( null ); alert(xmlHttp.responseText); the alert shows the mentioned data
Then you need to parse xmlHttp.responseText which is delivered as String. Within alert this is a String and not an array.
How do I do that? :( I am pretty new to java script.
|
0
var data = [{"Name":"A","Id":"1"},{"Name":"B","Id":"2"},{"Name":"C","Id":"3"}];

var result = {};
for (var i=0; i<data.length; i++) {
    for (var key in data[i]) {
        var item = data[i][key];
        if (key in result)
            result[key].push(item);
        else
            result[key] = [item];
    }
}

result.Name // ["A","B","C"]
result.Id // ["1","2","3"]

1 Comment

+1. The one who downvoted this probably doesn't understand generic solutions =p
0

You could use miso project if you are handling a lot of data with different source.

var ds = new Miso.Dataset({
  data: [ 
    { one : 1, two : 4, three : 7 },
    { one : 2, two : 5, three : 8 }
  ]
}).fetch({
  success: function() {
    log( this.column('one').data );
  }
});

http://misoproject.com/dataset/api.html#misodataset_i_fetch

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.