Poiro
Poiro

Reputation: 1011

Map JSON data model with Angular

I'm assuming I have an issue with my JSON data, but I can't seem to debug.

A snippet of data I get back from a service looks like:

   {
     "result" :{
       "version" : "0.1",
     },
     "recordData":{
       "carId": {
       "config": "auto",
       "val": "none"
     },
     "carName": {
       "config": "manual",
       "val": "bmw"
     }
   }

My Angular code looks like:

var modifyModel = function(data){
  return {
    carId: data.carId.val,
    carName: data.carName.val
  };
};

if (data.recordData){
  modeldata.results = data.recordData.map(modifyModel);
}
return modeldata;

I have the same code working on another JSON request, however the data comes across as an array, and the error I get back from the above is:

TypeError: data.recordData.map is not a function

So I guess I need to clean up the data I receive somehow?

Upvotes: 1

Views: 627

Answers (1)

Hiro
Hiro

Reputation: 23

to use a map function it only works on array. example:

var array = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}];
var reformattedArray = array.map(function(obj){ 
   var rObj = {};
   rObj[obj.key] = obj.value;
   return rObj;
});
// reformattedArray is now [{1:10}, {2:20}, {3:30}], 
// array is still [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}]

please see the documentation. Array.prototype.map()

Upvotes: 1

Related Questions