我有兩個對象,我想合併它們,但它不應該替換對象。在JavaScript中合併對象
var x = {'one':1, 'two': {'b': 2, 'c': 3}}
var y = {'two': {'b': 4}}
當我把它們合併的放出來應該是:
{'one':1, 'two': {'b': 4, 'c': 3}}
我有兩個對象,我想合併它們,但它不應該替換對象。在JavaScript中合併對象
var x = {'one':1, 'two': {'b': 2, 'c': 3}}
var y = {'two': {'b': 4}}
當我把它們合併的放出來應該是:
{'one':1, 'two': {'b': 4, 'c': 3}}
您可以使用遞歸方法用於更新嵌套對象。
var x = {
'one': 1,
'two': {
'b': 2,
'c': 3
}
}
var y = {
'two': {
'b': 4
}
}
function merge(a, b) {
// create new object and copy the properties of first one
var res = Object.assign({}, a);
//iterate over the keys of second object
Object.keys(b).forEach(function(e) {
// check key is present in first object
// check type of both value is object(not array) and then
// recursively call the function
if (e in res && typeof res[e] == 'object' && typeof res[e] == 'object' && !(Array.isArray(res[e]) || Array.isArray(b[e]))) {
// recursively call the function and update the value
// with the returned ne object
res[e] = merge(res[e], b[e]);
} else {
// otherwise define the preperty directly
res[e] = b[e];
}
});
return res;
}
var res = merge(x, y);
console.log(res);
UPDATE:如果你想在陣列合併,那麼你需要做這樣的事情。
var x = {
'one': 1,
'two': {
'b': [22, 23],
'c': 3
}
}
var y = {
'two': {
'b': [24]
}
}
function merge(a, b) {
var res = Object.assign({}, a);
Object.keys(b).forEach(function(e) {
if (e in res && typeof res[e] == 'object' && typeof res[e] == 'object' && !(Array.isArray(res[e]) || Array.isArray(b[e]))) {
res[e] = merge(res[e], b[e]);
// in case both values are array
} else if (Array.isArray(res[e]) && Array.isArray(b[e])) {
// push the values in second object
[].push.apply(res[e], b[e]);
// or use
// res[e] = res[e].concat(b[e]);
} else {
res[e] = b[e];
}
});
return res;
}
var res = merge(x, y);
console.log(res);
[有沒有這樣的事情JSON對象(http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json /)這些只是普通的JS對象。 – George