JSON字符串操作移除空串更改key/value的介绍

对于JSON字符串的操作。移除键值、添加属性。

//删除JSON对象value值

var json=[.....];

delete(json['key']);

或者

delete(json.key);

//添加对象object

json.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;

}

需要的就试试吧。

总结

以上是 JSON字符串操作移除空串更改key/value的介绍 的全部内容, 来源链接: utcz.com/z/332884.html

回到顶部