我有两个具有以下结构的 JavaScript 对象。
var obj1 = {id1: 10, name1: "stack"};
var obj2 = {id2: 20, name2: "overflow"};
我想使用 Javascript 将它们连接在一起作为一个单个对象(而不是数组)。
结果应该是这样的。
var res = {id: 10, name1: "stack", id2: 20, name2: "overflow"};
有没有一种简单的方法可以使用纯 JavaScript 来做到这一点?
注意:我不需要 jQuery 来执行此操作,我想 concat 用于 json 对象,而不是使用 concat
作为 json 数组。方法。有什么简单的方法或途径可以实现这一点吗?
最佳答案
var obj1 = {a: 1}, obj2 = {b:2}
// Using three arguments so that obj 1 and 2 aren't modified
var result = Object.assign({}, obj1, obj2);
// result.a -> 1
// result.b -> 2
// obj1.b -> undefined
// obj2.a -> undefined
// You could modify obj1
Object.assign(obj1, obj2);
// obj1.b -> 2
Polyfill :
if (typeof Object.assign != 'function') {
(function () {
Object.assign = function (target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
关于javascript - 如何使用 JavaScript 连接两个 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35869970/