對(duì)于JSON字符串的操作。移除鍵值、添加屬性。
//刪除JSON對(duì)象value值var json=[.....];delete(json['key']);或者delete(json.key);//添加對(duì)象objectjson.object=value;或者json['object']=value;
如果數(shù)據(jù)是查詢數(shù)據(jù)庫得到的,那么可能會(huì)存在空值,for循環(huán)JSON數(shù)據(jù)挨個(gè)移除空值或者操作數(shù)據(jù)比較繁瑣。
這時(shí)候可以使用for…in來循環(huán)屬性 去除空值或者操作數(shù)據(jù)。
 function removeEmptyObject(object){   for (var i in object) {  var value = object[i];  if (typeof value === 'object') {   if (Array.isArray(value)) {    if (value.length == 0) {     delete object[i];     continue;    }   }   removeEmptyObject(value);   //按需添加   if (isEmpty(value)) {    delete object[i];   }  } else {   if (value === '' || value === null || value === undefined) {    delete object[i];   } else {   }  } } return object;}//是否為空function isEmpty(object) { for (var name in object) {  return false; } return true;}操作組織架構(gòu)JSON數(shù)據(jù),移除空鍵值,子集內(nèi)容合并到新鍵children下。
 function removeEmptyObject(object){   for (var i in object) {    var value = object[i];    if (typeof value === 'object') {     if (Array.isArray(value)) {      if (value.length == 0) {        //alert(object[i]);       delete object[i];       continue;      }else{         var a=[];        if(i=='jobChildren'){          for (var j = 0; j < object[i].length; j++) {            a.push(object[i][j]);          }          delete object[i];        }else if(i=='userChildren'){          for (var j = 0; j < object[i].length; j++) {            a.push(object[i][j]);          }          delete object[i];         }else if(i=='deptChildren'){          for (var j = 0; j < object[i].length; j++) {            a.push(object[i][j]);          }          delete object[i];         }else if(i=='companyChildren'){          for (var j = 0; j < object[i].length; j++) {            a.push(object[i][j]);          }          delete object[i];         }else if(i=='jobDeptChildren'){          for (var j = 0; j < object[i].length; j++) {            a.push(object[i][j]);          }          delete object[i];        }        if(a.length>0&&object["children"]!=undefined){          for (var k = 0; k < object["children"].length; k++) {            a.push(object["children"][k]);          }          object["children"]=a;        }else if(a.length>0 && object["children"]==undefined){          object["children"]=a;        }       }     }     removeEmptyObject(value);     if (isEmpty(value)) {      delete object[i];     }    } else {     if (value === '' || value === null || value === undefined) {      delete object[i];     } else {     }    }   }  }  function isEmpty(object) {   for (var name in object) {    return false;   }   return true;  }需要的就試試吧。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)VeVb武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答