4

It is probably a simple solution, but I can not seem to get it working :/ I want to create a new "response" from results collected trough json/api call.

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"}

 ];

Stripping _id and changing "key". How can I go about doing it?

2 Answers 2

8

The Array.prototype.map function works wonders:

var newResponse = jsonResponse.map(function(item){
  return { heading : item.title, summary : item.desc };
});
Sign up to request clarification or add additional context in comments.

6 Comments

ES5 required. This will not work on older browsers. If that is a concern.
@SaintGerbil That is explained in the link i gave, under Browser Compatibility. There is also a polyfill available for browsers which don't implement Array.prototype.map.
console throwing me a : Uncaught TypeError: Object [{"..."}] has no method 'map' (I am developing (trying to at least) a mobile app).
@Tom Could you do a console.log(Array.prototype.map) for me?
@Tom then the problem is that your original object is not an array. If you will update the question to provide the exact shape of jsonResponse, i would be happy to give the correct answer.
|
4

Using Array.prototype.map is a great solution, but if you want to support older browsers, you can either use the map polyfill, 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's my jsFiddle

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.