获取 Key:Object 对并附加到 javascript 中的另一个对象

Take a Key:Object pair and append to another object in javascript

我有两个 javascript 对象。我想从第一个中取出一对 key:Object 并将其放入第二个中。

var first  = { a:1, b:2, c:{c1:11, c2:22, c3:33} }   
var second = { d:3, e:4 }

如何获得第三个 object 这样的?

{ d:3, e:4, c:{c1:11, c2:22, c3:33} }

这是最优雅的解决方案吗?

var third = second
third.c=first.c

我想避免重复 .c,例如 "take first.c and append both key and value to the second object"、

此解决方案假设您将键和值分开:Appending a key value pair to a json object 而这个 实际上添加了一个不属于另一个对象的新键。

你可以使用,它会改变对象

Object.assign(second, { c: first.c });

这个不会改变对象

var third = Object.assign({}, second, { c: first.c });

或传播运算符(您需要使用 Babel 对其进行转译)。

second = { ...second, { c: first.c });

您可以使用 Object.assign 并使用一个新对象作为结果。

var first  = { a: 1, b: 2, c: { c1: 11, c2: 22, c3: 33 } },
    second = { d: 3, e: 4 },
    third = Object.assign({}, second, { c: first.c });

console.log(third);

我建议 destructuring assignment for DRY code, namely the object property spread:

var third = {...second, c: first.c}; // ESNEXT

目前这是 stage 3 proposal considered for inclusion into the next JavaScript standard. For now, use Babel for backwards compatibility: Try it out.

如果你想通过引用复制,最简单的方法就是按照你所做的去做。

var third = second
third.c=first.c

但这也会使第二个有一个 'c' 属性。 对于一个干净的对象,一种方法是做

var third = Object.assign({}, first, second);
delete first.a
delete first.b

或者你可以这样做

var third = Object.assign({}, second)
third.c = Object.assign({}, first.c)

事实上,在 JavaScript 中,有几个选项可以将 属性 设置为一个对象:

  1. 使用简单的 .[] 符号,是最简单和最常用的方法。
  2. 使用Object.assign()方法。
  3. 使用 Object.defineProperty() and Object.defineProperties() 方法。

除了第三个选项 defineProperty()/defineProperties() 之外,您还可以使用 描述符 自定义这些额外的属性,例如 configurableenumerablewritablegetset 访问器,所有这些选项将做同样的事情并扩展 òbjectwith a new属性 `.

所以基本上没有什么优雅或者最合适的使用方式,全看情况了。


在您的具体情况下,避免分两行进行:

var third = second
third.c=first.c

你可以像这样更好地使用 Object.assign():

var third = Object.assign({}, second, { c: first.c });