Javascript creates a new array from json results

This is probably a simple solution, but I can't get it to work: / I want to create a new “answer” from the results compiled by calling json / api.

jsonResponse = [
     {"_id":"1","desc":"test desc","title":"Title 1"},
     {"_id":"2","title":"Title 2","desc":"desc 2"}
    ];

I need to create a new array from this that looks like this:

var newResponse = [ 
  { "heading" : "Title 1", "summary" : "test desc"},
  { "heading" : "Title 2", "summary" : "desc 2"}

 ];

Removing _id and changing the "key". How can i do this?

+4
source share
2 answers

The Array.prototype.map function works wonders:

var newResponse = jsonResponse.map(function(item){
  return { heading : item.title, summary : item.desc };
});
+8
source

Using Array.prototype.mapis a great solution, but if you want to support older browsers, you can use mappolyfill or do this:

var newData = function () {
    var myArray = [];
    for (var i = 0; i < JSON.length; i++) {
        var self = JSON[i];
        myArray.push({
            heading: self.title,
            summary: self.desc
        });
    }
    return myArray;
};

// output
newData();

Here my jsFiddle

+4
source

All Articles