在 ES6 中追加对象?

Append objects in ES6?

在我的 React 本机应用程序中,我在本地存储了一个对象并检索了它,工作正常但现在我想将另一个对象附加到前一个对象,就像我有两个对象一样:

    const obj1 = {key1: keyone, key2: keytwo}
    const obj2 = {key4: keyfour, key6: keysix}

我想要的只是一个对象

    { key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }

我正在尝试这样做:

    const newVal = `${obj1}, ${obj2}`

哪个returns"object Object"

我经历了 Object.assign() 以及 lodash 的 .merge() 功能,但它们似乎正在合并对象中的公共字段。

我该如何实现?

您有一个对象 A = {"a": 1, "b": 2} 和一个对象 B = {"c": 3, "d": 4}。您想要一个 C 的对象 包含两个单独的对象 (因此您问题中的语法):

var C = {A, B}; //{{"a": 1, "b": 2}, {"c": 3, "d": 4}}

1.如果你想要一个对象数组,那么你可以使用这种方法:

const arr = [obj1, obj2];

它将为您提供以下结果:

[{ key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }] 

2。如果你想拥有对象的对象那么你可以试试这个:

const arr = {obj1, obj2};

这导致以下结果:

{ obj1: { key1: keyone, key2: keytwo }, obj2: { key4: keyfour, key6: keysix }} 

3。如果你想要一个单一的对象,你可以试试这个:

const arr = {...obj1, ...obj2};

将产生以下结果:

 { key1: keyone, key2: keytwo, key4: keyfour, key6: keysix }

您可以使用扩展运算符 (...)

const obj1 = {key1: 1, key2: 2};
const obj2 = {key4: 4, key6: 6};

const newVal = {...obj1, ...obj2 };

console.log(newVal);

你想要的输出是一个对象本身包含两个没有键的对象,我的建议是输出一个对象数组,这对你的输出有一定的影响。

[obj1, obj2] = [{ key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }]