JavaScript 覆盖对象字段级别
下列的代码可以实现a和b两个对象进行覆盖合并,不同于object.asgin 会覆盖。下列的代码只会字段级覆盖。
javascript
/**
* 把source的字段,覆盖设置到target的字段,递归覆盖,不直接覆盖对象
* @param target
* @param source
*/
function extend(target, source) {
for (let key in source) {
let newValue = source[key];
let oldValue = target[key];
//如果 是数组,有值就追加,没值就覆盖
if (Array.isArray(oldValue)) {
target[key] = [...oldValue, ...newValue];
} else if (typeof (oldValue) == "object") {
//如果是object 递归设置
target[key] = extend(oldValue, newValue);
} else {
//判断,如果不是object,就直接设置
//普通字段
target[key] = newValue;
}
}
return target
}
var a = {
obj: {
name: '张三',
age: 18,
student: {
name: '王五',
classes: {
name: '1年级1班',
teacher: {
name: '王老师',
age: 20
}
}
}
},
array: [{
c: 13
}, {
b: 22
}],
aint: 10,
astring: '123'
}
var b = {
obj: {
name: '李四',
aaa: '555',
student: {
ss: '321',
classes: {
aget: 18,
teacher: {
age: 30
}
}
}
}
}
// let temp = Object.assign(a, b);
let temp = extend(a, b);
console.log(JSON.stringify(temp, "", "\t"));
/**
* 把source的字段,覆盖设置到target的字段,递归覆盖,不直接覆盖对象
* @param target
* @param source
*/
function extend(target, source) {
for (let key in source) {
let newValue = source[key];
let oldValue = target[key];
//如果 是数组,有值就追加,没值就覆盖
if (Array.isArray(oldValue)) {
target[key] = [...oldValue, ...newValue];
} else if (typeof (oldValue) == "object") {
//如果是object 递归设置
target[key] = extend(oldValue, newValue);
} else {
//判断,如果不是object,就直接设置
//普通字段
target[key] = newValue;
}
}
return target
}
var a = {
obj: {
name: '张三',
age: 18,
student: {
name: '王五',
classes: {
name: '1年级1班',
teacher: {
name: '王老师',
age: 20
}
}
}
},
array: [{
c: 13
}, {
b: 22
}],
aint: 10,
astring: '123'
}
var b = {
obj: {
name: '李四',
aaa: '555',
student: {
ss: '321',
classes: {
aget: 18,
teacher: {
age: 30
}
}
}
}
}
// let temp = Object.assign(a, b);
let temp = extend(a, b);
console.log(JSON.stringify(temp, "", "\t"));