js处理数据的小技巧1
json数组更换对应的key
在使用组件的时候,项目中经常会碰到后台返回给我们的json对象的键名(key)和组件中需要的数据名称不一致的问题,我们需要整体替换键名
例如
let listArr = [
{id: '01', name: 'zhangsan', age: '15', childArr: [{id: '0101', name: 'zhangxiaosan', age: '5'},
{id: '0102', name: 'zhangxiaosan1',age: '6'}]},
{id: '02', name: '李四', age: '15'},
{id: '03', name: '王五', age: '15',
childArr: [{id: '0301', name: '王五1', age: '5'},
{id: '0302', name: '王五2',age: '6'}]
}
]
但是我们在使用中组件要用到的是key和label 而不是 id 和 name,所以要把这个数组对象的集体更换
我们使用的方法是replace方法
let newList = JSON.parse(JSON.stringify(listArr).replace(/id/g,'key').replace(/name/,'label'))
console.log(newList)
//[{"key":"01","name":"zhangsan","age":"15","childArr":[{"key":"0101","name":"zhangxiaosan","age":"5"},{"key":"0102","name":"zhangxiaosan1","age":"6"}]},{"key":"02","name":"李四","age":"15"},{"key":"03","name":"王五","age":"15","childArr":[{"key":"0301","name":"王五1","age":"5"},{"key":"0302","name":"王五2","age":"6"}]}]
JQuery的serializeObject 序列化form表单
//封装一个方法: serializeObject() ——返回对象
$.fn.serializeObject = function(){
var jsonObj = {};
var a = this.serializeArray();
$.each(a, function() {
if (jsonObj[this.name]) {
if (!jsonObj[this.name].push) {
jsonObj[this.name] = [jsonObj[this.name]];
}
jsonObj[this.name].push(this.value || '');
} else {
jsonObj[this.name] = this.value || '';
}
});
return jsonObj;
};
实现深拷贝(递归拷贝)
function deepClone(parent, c){
let child = c || {};
for(let key in parent) {
if(parent.hasOwnProperty(key)){
let val = parent[key];
if(typeof val === 'object'){
child[key] = object.prototype.tostring.call("val") === "[object Array]"? []: {};
deepClone(val, child[key])
} else {
child[key] = parent[key]
}
}
}
return child;
}
做项目用到了一个数组的处理方法,
var arr = [{date: "2015-05-04", count: "1200"},{date: "2015-06-04", count: "1200"},{date: "2015-07-04", count: "1200"},{date: "2015-08-04", count: "1200"},{date: "2015-09-04", count: "1200"}]
//在项目中我用到echarts,日期要放到x轴,数量也要提取出来
//我要对这个数据进行处理
var dateArr = arr.map(item=>{return item.date}) //获取到所有的日期组成的一个数组
后续应该还有补充,以后技术需要可以直接用