我正在寻找“添加”多个JavaScript对象(关联数组)的最佳方法。
例如,给定:
a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };
计算的最佳方式是什么:
{ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
答案 0 :(得分:120)
ECMAscript 6引入Object.assign()
以在Javascript中本地实现此目的。
Object.assign()方法用于将所有可枚举的自有属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
MDN documentation on Object.assign()
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
Object.assign
is supported in many modern browsers但还不是全部。使用Babel和Traceur等转录程序生成向后兼容的ES5 JavaScript。
答案 1 :(得分:34)
答案 2 :(得分:33)
这应该这样做:
function collect() {
var ret = {};
var len = arguments.length;
for (var i=0; i<len; i++) {
for (p in arguments[i]) {
if (arguments[i].hasOwnProperty(p)) {
ret[p] = arguments[i][p];
}
}
}
return ret;
}
输入:
a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };
d = collect(a, b, c);
console.log(d);
输出:
Object one=1 two=2 three=3 four=4 five=5
答案 3 :(得分:14)
ECMAScript 6有spread operator。现在你可以这样做:
const obj1 = {1: 11, 2: 22}
const obj2 = {3: 33, 4: 44}
const obj3 = {...obj1, ...obj2}
console.log(obj3)
// {1: 11, 2: 22, 3: 33, 4: 44}
答案 4 :(得分:12)
Underscore几乎没有办法做到这一点;
<强> 1。 _.extend(destination, *sources)
将来源对象中的所有属性复制到目标对象,然后返回目标对象。
_.extend(a, _.extend(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
或者
_.extend(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.extend(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
<强> 2。 _.defaults(object, *defaults)
使用默认值对象中的值填充对象中的未定义属性,然后返回对象。< / p>
_.defaults(a, _.defaults(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
或者
_.defaults(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.defaults(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
答案 5 :(得分:4)
为什么要将函数限制为3个参数?另外,请检查hasOwnProperty
。
function Collect() {
var o={};
for(var i=0;i<arguments.length;i++) {
var arg=arguments[i];
if(typeof arg != "object") continue;
for(var p in arg) {
if(arg.hasOwnProperty(p)) o[p] = arg[p];
}
}
return o;
}
答案 6 :(得分:3)
function Collect(a, b, c) {
for (property in b)
a[property] = b[property];
for (property in c)
a[property] = c[property];
return a;
}
注意:以前的对象中的现有属性将被覆盖。
答案 7 :(得分:3)
使用比Object.assign()短的语法,现在可以进行浅克隆(不包括原型)或合并对象。
在Spread syntax中引入了object literals的const a = { "one": 1, "two": 2 };
const b = { "three": 3 };
const c = { "four": 4, "five": 5 };
const result = {...a, ...b, ...c};
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }
many modern browsers支持Spread(...)运算符,但并非全部。
因此,建议使用transpiler之类的Babel在当前和较旧的浏览器或环境中将ECMAScript 2015+代码转换为JavaScript的向后兼容版本。
这是您的等效代码Babel will generate:
"use strict";
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var a = { "one": 1, "two": 2 };
var b = { "three": 3 };
var c = { "four": 4, "five": 5 };
var result = _extends({}, a, b, c);
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }
答案 8 :(得分:2)
要合并动态数量的对象,可以将Object.assign
与spread syntax结合使用。
const mergeObjs = (...objs) => Object.assign({}, ...objs);
上面的函数接受任意数量的对象,将它们的所有属性合并到一个新对象中,后面的对象将覆盖以前的对象。
演示:
const mergeObjs = (...objs) => Object.assign({}, ...objs);
const a = {prop: 1, prop2: '2'},
b = {prop3: 3, prop4: [1,2,3,4]}
c = {prop5: 5},
d = {prop6: true, prop7: -1},
e = {prop1: 2};
const abcd = mergeObjs(a,b,c,d);
console.log("Merged a,b,c,d:", abcd);
const abd = mergeObjs(a,b,d);
console.log("Merged a,b,d:", abd);
const ae = mergeObjs(a,e);//prop1 from e will overwrite prop1 from a
console.log("Merged a,e:", ae);
要合并对象数组,可以应用类似的方法。
const mergeArrayOfObjs = arr => Object.assign({}, ...arr);
演示:
const mergeArrayOfObjs = arr => Object.assign({}, ...arr);
const arr = [
{a: 1, b: 2},
{c:1, d:3},
{abcd: [1,2,3,4], d: 4}
];
const merged = mergeArrayOfObjs(arr);
console.log(merged);
答案 9 :(得分:1)
Probably, the fastest, efficient and more generic way is this (you can merge any number of objects and even copy to the first one ->assign):
function object_merge(){
for (var i=1; i<arguments.length; i++)
for (var a in arguments[i])
arguments[0][a] = arguments[i][a];
return arguments[0];
}
It also allows you to modify the first object as it passed by reference. If you don't want this but want to have a completely new object containing all properties, then you can pass {} as the first argument.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge(object1,object2,object3);
combined_object and object1 both contain the properties of object1,object2,object3.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge({},object1,object2,object3);
In this case, the combined_object contains the properties of object1,object2,object3 but object1 is not modified.
Check here: https://jsfiddle.net/ppwovxey/1/
Note: JavaScript objects are passed by reference.
答案 10 :(得分:1)
最简单:传播运营商
var obj1 = {a: 1}
var obj2 = {b: 2}
var concat = { ...obj1, ...obj2 } // { a: 1, b: 2 }
答案 11 :(得分:0)
ES6 ++
问题是将各种不同的对象添加到一个。
let obj = {};
const obj1 = { foo: 'bar' };
const obj2 = { bar: 'foo' };
Object.assign(obj, obj1, obj2);
//output => {foo: 'bar', bar: 'foo'};
假设您有一个具有多个对象的对象:
let obj = {
foo: { bar: 'foo' },
bar: { foo: 'bar' }
}
这是我找到的解决方案(仍然需要预告:/)
let objAll = {};
Object.values(obj).forEach(o => {
objAll = {...objAll, ...o};
});
通过这样做,我们可以动态地将所有对象键添加到一个。
// Output => { bar: 'foo', foo: 'bar' }
答案 12 :(得分:-1)
function collect(a, b, c){
var d = {};
for(p in a){
d[p] = a[p];
}
for(p in b){
d[p] = b[p];
}
for(p in c){
d[p] = c[p];
}
return d;
}