2016-03-08 67 views
0

我有两个JavaScript对象,其结构如下。如何用JavaScript连接两个JavaScript对象

var obj1 = {id1: 10, name1: "stack"}; 
var obj2 = {id2: 20, name2: "overflow"}; 

欲使用Javascript一起Concat的它们作为一个单一对象(未数组)。

结果应该是这样的。

var res = {id: 10, name1: "stack", id2: 20, name2: "overflow"}; 

有没有一种简单的方法来使用纯JavaScript做到这一点?

注:我不需要jQuery来做到这一点,我想concat是用于json对象,而不是用jQuery数组使用concat方法。有没有简单的方法或方法来实现这一点?

+1

在ES6中,您可以使用Object.assign。例如:'Object.assign({},obj1,obj2)' –

+0

换句话说:在这个问题中没有JSON。 JSON是数据交换的文本符号。如果你正在处理JavaScript源代码,而不是处理*字符串*,那么你并没有处理JSON。 –

回答

3

使用Object.assign

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; 
    }; 
    })(); 
} 
+0

谢谢胡安!使用var result = Object.assign({},obj1,obj2)有什么区别;和var result = Object.assign(obj1,obj2);两者都给出了相同的结果right –

+0

@UI_Dev:正如他在回答中的评论中所说:后者改变了'obj1'。前者不。 –

+0

评论应该清楚吗? –

0

简单的纯溶液:

function addToObject(source, target) { 
 
    Object.keys(source).forEach(function (k) { 
 
     target[k] = source[k]; 
 
    }); 
 
} 
 

 
var obj1 = { id1: 10, name1: "stack" }, 
 
    obj2 = { id2: 20, name2: "overflow" }, 
 
    result = {}; 
 

 
addToObject(obj1, result); 
 
addToObject(obj2, result); 
 
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');