Narendra Kumar
Narendra Kumar

Reputation: 91

How to change/add field in JSON structure in angularjs/javascript

i am using angularjs http get method to get the data,the JSON format which i am getting is :

{"SITE1":[
    {
        "name":"name1",
        "status":"0",
        "id":23,
        "isDeleted":false
    },
    {
        "name":"name2",
        "status":"0",
        "id":13,
        "isDeleted":false
    }],

"SITE2":[
    {
        "name":"name3",
        "status":"0",
        "id":2,
        "isDeleted":false
    }
    ]}

but i want data to be in format

{"location" : "SITE1",
 "services" : [
      {
        "name":"name1",
        "status":"0",
        "id":23,
        "isDeleted":false
      },
      {
        "name":"name2",
        "status":"0",
        "id":13,
        "isDeleted":false
      }],
   "location" : "SITE2",
    "services":[
       {
        "name":"name3",
        "status":"0",
        "id":2,
        "isDeleted":false
       }
    ]}

Please help in this, how to do this. I tried using

object["location"] = key;
 object["status"] = value;

to add these fields. but something is going wrong in this.

Upvotes: 0

Views: 3439

Answers (1)

valepu
valepu

Reputation: 3315

Your request won't work, as stated by "Nowhere man" because you are setting different values to the same key at the moment so that only the last one will be shown. The best solution in my opinion is to have an array of objects.

var temp=[];
angular.forEach(values, function(data, index){
    var tempObj={};
    tempObj.location=index;
    tempObj.services=data;
    temp.push(tempObj);
});
return temp;

See this plunkr http://plnkr.co/edit/5UdDEl?p=preview

Upvotes: 2

Related Questions