假如我们定义的一组数据是这样的:
var data = {
name: "张三",
age: 10,
mary: false,
likes: ["苹果", "香蕉", "梨子"],
friend: [
{
name: "李四",
age: 13,
mary: false,
likes: ["榴莲", "椰子", "梨子"],
info: {
phone: 15645454,
idcard: "34062318960828101x",
address: ["地址1", "地址2", "地址3"],
skill: [
{
name: "篮球",
level: "12"
},
{
name: "足球",
level: "2"
},
{
name: "羽毛球",
level: "5"
}
]
}
},
{
name: "王五",
age: 18,
mary: true,
likes: ["草莓", "香蕉", "芒果"],
info: {
phone: 15645454,
idcard: "34062318960828102x",
address: ["地址1", "地址2", "地址3"],
skill: [
{
name: "篮球",
level: "12"
},
{
name: "足球",
level: "2"
},
{
name: "羽毛球",
level: "5"
}
]
}
},
{
name: "赵六",
age: 15,
mary: false,
likes: ["荔枝", "西瓜", "梨子"],
info: {
phone: 15645454,
idcard: "34062318960828103x",
address: ["地址1", "地址2", "地址3"],
skill: [
{
name: "篮球",
level: "12"
},
{
name: "足球",
level: "2"
},
{
name: "羽毛球",
level: "5"
}
]
}
},
],
info: {
phone: 15645454,
idcard: "34062318960828100x",
address: ["地址1", "地址2", "地址3"],
skill: [
{
name: "篮球",
level: "12"
},
{
name: "足球",
level: "2"
},
{
name: "羽毛球",
level: "5"
}
]
}
}
现在我们想要清除这组数据的内容达到一个初始化的效果,我们可以这样写:
// 递归删除
/**
* 递归删除对象属性的值
* @param {[type]} obj [对象]
* @param {[type]} clearArray [false/true] //是否直接清空对象内数组的内容
* @return {[type]} [description]
*/
function deleteKeysValue(obj, clearArray) {
for (var key in obj) {//遍历对象/数组里的每个属性名
if (Object.prototype.toString.call(obj[key]) === '[object Object]') { //如果该对象属性值是个对象
deleteKeysValue(obj[key], clearArray);//再调用一次遍历
}else if (Object.prototype.toString.call(obj[key]) === '[object Array]') {//如果该对象属性值是个数组
if (clearArray) {//判断是否直接清空对象内数组的内容
obj[key] = [];
} else {
deleteKeysValue(obj[key], clearArray);//如果不清空数组,那就再遍历一遍
}
}else{//剩下的情况(不是数组也不是对象)
if (typeof obj[key] === 'string') {//字符串
obj[key] = ''
} else if (typeof obj[key] === 'number') {//数字类型
obj[key] = 0
} else if (typeof obj[key] === 'boolean') {//布尔类型
obj[key] = false
}
}
// vue 调用增加return 及接收
}
}
//打印原先的数组
console.log("data")
console.log(data)
//打印处理后的数组(清空所有数组里的对象)
let data2=JSON.parse(JSON.stringify(data))//深拷贝
console.log("deleteKeysValue(data2,true)")
deleteKeysValue(data2, true)
console.log(data2)
//打印处理后的数组(保留所有数组里的对象并初始化)
// let data3=JSON.parse(JSON.stringify(data))//深拷贝
// console.log("deleteKeysValue(data3,false)")
// deleteKeysValue(data3, false)
// console.log(data3)
原先的data打印出来是这样的:
经过函数处理后我们可以看到这个对象的数据被重置了,数组里的内容也清空了
当然,我们也可以保留数组里的内容并初始化它:
例子中打印的时候加JSON.parse(JSON.stringify(data))是因为有深浅拷贝问题,科普可以参考这篇文章:
https://www.jianshu.com/p/cd829908f3d2