简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM