如何连接多个 JavaScript 对象的属性 [英] How to concatenate properties from multiple JavaScript objects

查看:36
本文介绍了如何连接多个 JavaScript 对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找添加"多个 JavaScript 对象(关联数组)的最佳方法.

I am looking for the best way to "add" multiple JavaScript objects (associative arrays).

例如,给定:

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 }

推荐答案

ECMAscript 6 引入了 Object.assign() 以在 Javascript 中实现这一点.

ECMAscript 6 introduced Object.assign() to achieve this natively in Javascript.

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.它将返回目标对象.

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 文档

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 支持许多现代浏览器,但还不是全部.使用像 BabelTraceur 生成向后兼容的 ES5 JavaScript.

Object.assign is supported in many modern browsers but not yet all of them. Use a transpiler like Babel and Traceur to generate backwards-compatible ES5 JavaScript.

这篇关于如何连接多个 JavaScript 对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆