对于JSON字符串的操作。移除键值、添加属性。
//删除JSON对象value值var json=[.....];delete(json['key']);或者delete(json.key);//添加对象objectjson.object=value;或者json['object']=value;
如果数据是查询数据库得到的,那么可能会存在空值,for循环JSON数据挨个移除空值或者操作数据比较繁琐。
这时候可以使用for…in来循环属性 去除空值或者操作数据。
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;}
操作组织架构JSON数据,移除空键值,子集内容合并到新键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; }
需要的就试试吧。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对武林网的支持。如果你想了解更多相关内容请查看下面相关链接
新闻热点
疑难解答