时间:2018-04-16 20:33:33

标签: javascript reactjs

我有2个javascript对象,第一个是默认对象,第二个是第一个的覆盖。

对象1:

export const messages = {
'id': 'id',
'category': 'category',
'country': 'country',
'continent': 'continent',
'city': 'city',
'field': 'field',
'price': 'price',
'name': 'name',

};

对象2:

window.messages['id'] = 'id';
window.messages['category'] = 'section';
window.messages['country'] = 'country';

这看起来很愚蠢,但有理由这种荒谬

我想知道是否有办法让我用对象2覆盖对象1而不会破坏对象1.这些都是外部文件。

我为我糟糕的拼写和描述道歉

提前谢谢你

1 个答案:

答案 0 :(得分:1)

据我所知,你需要以一种简单的方式将object2合并到object1中。

let obj1 = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3'
}

let obj2 = {
  key1: 'anotherValue1',
  key2: 'anotherValue2'
}

let mergedObjVariant1 = Object.assign(obj1, obj2); // variant#1
let mergedObjVariant2 = {...obj1, ...obj2};        // variant#2

因此,您将拥有以下两种变体:

{ key1: 'anotherValue1', key2: 'anotherValue2', key3: 'value3' }