写页面的时候一直没整明白为什么吗对象格式的要通过JSON.stringify()这个方法转一下有什么好处,最近看其它的博客get到一些实用的技巧
第一种:在数组中提取数据
var data = [{
name: "程咬金",
sex: "1",
age: 26
},
{
name: "程才",
sex: "0",
age: 20
},
{
name: "程新松",
sex: "1",
age: 22
},
{
name: "程功",
sex: "1",
age: 18
}
];
如果这里我们只想提取name 和 sex
我们常用的方法可能是
var new_data = JSON.stringify(data,['name','sex']);
console.log(new_data);
输出结果
[{"name":"程咬金","sex":"1"},{"name":"程才","sex":"0"},{"name":"程新松","sex":"1"},{"name":"程功","sex":"1"}]
第二种用法:修改数据
例如我们要把sex为0改为女 sex为1改为男
var str_json = JSON.stringify(data,function(key,value){
if(key == 'sex'){
return ["女",'男'][value];
}
return value;
});
console.log(str_json);
输出结果
[{"name":"程咬金","sex":"男","age":26},{"name":"程才","sex":"女","age":20},{"name":"程新松","sex":"男","age":22},{"name":"程功","sex":"男","age":18}]
value的值是data中对象sex的值,而这个['女','男']数组,是根据[value]的索引对应到[‘女’,‘男’],也就是说当value为0,[value]即为[0],对应到数组['女','男']的索引0,值即为‘女’。比如我定义8--男,9--女;
var data =[
{
name: "程咬金",sex:"8",age:26
},
{
name: "程才",sex:"9",age:20
},
{
name: "程新松",sex:"8",age:22
},
{
name: "程功",sex:"8",age:18
}
];
/*回调函数做一个映射关系*/
var str_json = JSON.stringify(data,function(key,value){
if(key == 'sex'){
return ['男','女'][value-8];
}
return value;
});
console.log(str_json);