简体   繁体   中英

Update key and value - json object

I have a form with a miltiple select element along with other input and select elements. I have access to the post data object before submiting to the server and I want to modify the post data before allowing it to reach the server.

If no options are selected in my multiple select called equipments the value is " null " here is what the post data looks like.

({roomNumber:"As369", minCapacity:"1", maxCapacity:"10", capacity:"8", campus:"1", equipments:null, roomGrid_id:"127"})

If equipments is null, I want to change the key from "equipments" to "equipments[]" and the value from "null" to and empty array. You see my actuon expects "equipments[]". Ideally, if there is atleast one selected item in the multiple select here is what the postdata will look like.

({roomNumber:"As369", minCapacity:"1", maxCapacity:"10", capacity:"8", campus:"1", equipments:["2"], roomGrid_id:"127"})

Any Ideas ? I was thinking about simply adding a new key:value pair called equipments:[]

var obj = {
    roomNumber:"As369",
    minCapacity:"1", 
    maxCapacity:"10", 
    capacity:"8", 
    campus:"1", 
    equipments:null, 
    roomGrid_id:"127"
} 

 if(obj["equipments"] === null ) {
      delete obj["equipments"];
      obj["equipments[]"] = [] 
   }

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