Rkumar Rkumar - 4 months ago 10
Javascript Question

How to save JSON string array with multiple name/value pair in separate arrays in JavaScript

I have following JSON string.

[ { "id" : "1", "name" : "name1" },
{ "id" : "2", "name" : "name2" },
{ "id" : "3", "name" : "name3" },
{ "id" : "4", "name" : "name4" },
{ "id" : "5", "name" : "name5" } ]


How to save it in 2 separate arrays of "id & "name", where id and name arrays have same data as in the original array on a particular index.

Answer
var data = [ { "id" : "1", "name" : "name1" },
{ "id" : "2", "name" : "name2" },
{ "id" : "3", "name" : "name3" },
{ "id" : "4", "name" : "name4" },
{ "id" : "5", "name" : "name5" } ];

var ids = data.map(function(obj){
      return obj.id;
});

var names = data.map(function(obj){
      return obj.name;
});

Use map function