关于json对象的删除
摘自 http://www.cnblogs.com/wuyifu/p/3424621.html
一个json对象在后台产生了,但是有些数据可能无效或者不合法,所以需要在前台作些例外处理,比如删除掉。
json的删除有很多种,直接用过 delete json对象方式。
举例如下
Js代码
var columns = [
{name:"bigTitle",caption:reportData.bigTitle,children:[
{name:"orgName",caption:"组织结构名称",width:100,mode:"string"},
{name:"helpinfo",caption:reportData.columnCaption[0],
children:[{name:"workday_month",caption:"工作日数",width:80,mode:"number",format:"#"},
{name:"loggedday_month",caption:"登录天数",width:80,mode:"number",format:"#"}]
},
{name:"helpinfo",caption:reportData.columnCaption[1],
children:[{name:"workday_week1",caption:"工作日数",width:70,mode:"number",format:"#"},
{name:"loggedday_week1",caption:"登录天数",width:70,mode:"number",format:"#"}]
},
{name:"helpinfo",caption:reportData.columnCaption[2],
children:[{name:"workday_week2",caption:"工作日数",width:70,mode:"number",format:"#"},
{name:"loggedday_week2",caption:"登录天数",width:70,mode:"number",format:"#"}]
},
{name:"helpinfo",caption:reportData.columnCaption[3],
children:[{name:"workday_week3",caption:"工作日数",width:70,mode:"number",format:"#"},
{name:"loggedday_week3",caption:"登录天数",width:70,mode:"number",format:"#"}]
},
{name:"helpinfo",caption:reportData.columnCaption[4],
children:[{name:"workday_week4",caption:"工作日数",width:70,mode:"number",format:"#"},
{name:"loggedday_week4",caption:"登录天数",width:70,mode:"number",format:"#"}]
},
{name:"helpinfo",caption:reportData.columnCaption[5],
children:[{name:"workday_week5",caption:"工作日数",width:70,mode:"number",format:"#"},
{name:"loggedday_week5",caption:"登录天数",width:70,mode:"number",format:"#"}]
}
]}
];
根据rtData.columnCaption 判断,如果为null,则删除该节点,不予显示。
用过 delete columns[0]['children'][6];
无效,报js错误,后来发现 删除确实是删除了,但是最后还遗留了一个逗号,导致IE下报错,查了很多资料无解。
最后换了个解决方法。
columns[0]['children'].pop();
pop()方法表示删除最后一个节点。
工作日历的要求正好满足该要求,从后递减。
其他类似的方法有如下:
var person={name:"yaoMing",sex:"m",age:"26"};
jsonObj2.persons.push(person);//数组最后加一条记录
jsonObj2.persons.pop();//删除最后一项
jsonObj2.persons.shift();//删除第一项
jsonObj2.persons.unshift(person);//数组最前面加一条记录
只要适合Javascript的方法都是可以用在JSON对象的数组中的!所以还有另外的方法splice( )进行crud操作!
//删除
jsonObj2.persons.splice(0,1);//开始位置,删除个数
//替换不删除
var self={name:"tom",sex:"m",age:"24"};
var brother={name:"Mike",sex:"m",age:"29"};
jsonObj2.persons.splice(1,0,self,brother);//开始位置,删除个数,插入对象
//替换并删除
var self={name:"tom",sex:"m",age:"24"};
var brother={name:"Mike",sex:"m",age:"29"};
jsonObj2.persons.splice(0,1,self,brother);//开始位置,删除个数,插入对象