如何连接多个 JavaScript 对象的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2454295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to concatenate properties from multiple JavaScript objects
提问by Vlad
I am looking for the best way to "add" multiple JavaScript objects (associative arrays).
我正在寻找“添加”多个 JavaScript 对象(关联数组)的最佳方法。
For example, given:
例如,给定:
a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };
what is the best way to compute:
什么是最好的计算方法:
{ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
回答by filoxo
ECMAscript 6 introduced Object.assign()to achieve this natively in Javascript.
引入 ECMAscript 6Object.assign()以在 Javascript 中本地实现这一点。
The Object.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
所述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.assignis supported in many modern browsersbut not yet all of them. Use a transpiler like Babeland Traceurto generate backwards-compatible ES5 JavaScript.
Object.assign许多现代浏览器都支持,但还不是全部。使用像Babel和Traceur 这样的转译器来生成向后兼容的 ES5 JavaScript。
回答by Vlad
回答by cletus
This should do it:
这应该这样做:
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;
}
let a = { "one" : 1, "two" : 2 };
let b = { "three" : 3 };
let c = { "four" : 4, "five" : 5 };
let d = collect(a, b, c);
console.log(d);
Output:
输出:
{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5
}
回答by valex
ECMAScript 6 has spread syntax. And now you can do this:
ECMAScript 6 具有扩展语法。现在你可以这样做:
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}
回答by gihanchanuka
Underscorehas few methods to do this;
Underscore几乎没有方法可以做到这一点;
1. _.extend(destination, *sources)
Copy all of the properties in the sourceobjects over to the destinationobject, and return the destinationobject.
将源对象中的所有属性复制到目标对象,并返回目标对象。
_.extend(a, _.extend(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
Or
或者
_.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)
2. _.defaults(object, *defaults)
Fill in undefinedproperties in objectwith values from the defaultsobjects, and return the object.
使用默认对象中的值填充object中未定义的属性,并返回object。
_.defaults(a, _.defaults(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
Or
或者
_.defaults(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.defaults(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
回答by Thiago Santos
Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().
浅克隆(不包括原型)或合并对象现在可以使用比Object.assign()更短的语法。
Spread syntaxfor object literalswas introduced in ECMAScript 2018):
ECMAScript 2018中引入了对象字面量的扩展语法):
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 }
Spread (...) operatoris supported in many modern browsersbut not all of them.
许多现代浏览器都支持Spread (...) 运算符,但并非所有浏览器都支持。
So, it is recommend to use a transpilerlike Babelto convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
因此,它是推荐使用transpiler像巴贝尔在ECMAScript 2015+代码转换为当前和旧的浏览器或环境中的JavaScript的向后兼容的版本。
This is the equivalent code Babel will generatefor you:
"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 }
回答by Alsciende
Why should the function be restricted to 3 arguments? Also, check for hasOwnProperty.
为什么该函数应限制为 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;
}
回答by Bj?rn
function Collect(a, b, c) {
for (property in b)
a[property] = b[property];
for (property in c)
a[property] = c[property];
return a;
}
Notice: Existing properties in previous objects will be overwritten.
注意:先前对象中的现有属性将被覆盖。
回答by Selay
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):
可能,最快、有效和更通用的方法是这样的(你可以合并任意数量的对象,甚至复制到第一个 ->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.
combine_object 和 object1 都包含 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.
在这种情况下,combined_object 包含 object1、object2、object3 的属性,但 object1 没有被修改。
Check here: https://jsfiddle.net/ppwovxey/1/
在这里查看:https: //jsfiddle.net/ppwovxey/1/
Note: JavaScript objects are passed by reference.
注意:JavaScript 对象是通过引用传递的。
回答by Purkhalo Alex
It's easy using ES7 spread operatorfor an object, in your browser console put
对对象使用ES7 扩展运算符很容易,在您的浏览器控制台中放置
({ name: "Alex", ...(true ? { age: 19 } : { })}) // {name: "Alex", age: 19}
({ name: "Alex", ...(false ? { age: 19 } : { })}) // {name: "Alex", }

