-1

So I have 2 objects:

Object A

{
    key1 : 'key1',
    key2 : 'key2'
}

Object B

{
    key1 : 'override a'
}

And I want to merge them like this:

result

{
    key1 : 'override a',
    key2 : 'key2'
}

Has anybody got a suggestion how to do this in TypeScript (or plain JS)

fransyozef
  • 544
  • 2
  • 7
  • 18
  • 1
    `{ ...A, ...B }`? – jonrsharpe Mar 24 '18 at 09:15
  • 2
    Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – Alexander Mar 24 '18 at 09:21
  • Use your favourite search engine with "merge javascript objects with Typescript?" and you would have found the answer. – str Mar 24 '18 at 09:35

5 Answers5

1

Object.assign() can be leveraged to merge objects.

See below for a practical example.

// Input.
const A = {key1 : 'key1', key2 : 'key2'}
const B = {key1 : 'override a'}

// Assign.
const merge = (...args) => Object.assign({}, ...args)

// Output.
const output = merge(A, B)

// Proof.
console.log(output)
Arman Charan
  • 5,669
  • 2
  • 22
  • 32
0

You could use Object.assign() method:

var merged = Object.assign({}, objectA, objectB);
Alexander
  • 4,420
  • 7
  • 27
  • 42
0

var objectA={key1:1}
var objectB={key1:2,key2:3};
//create new object and merge the two object which will not affect the original object

var newObject = Object.assign({}, objectA, objectB);
console.log(newObject);
//merging in the original object
Object.assign(objectA,objectB);
console.log(objectA);
John Willson
  • 444
  • 1
  • 3
  • 13
-1

const c: any = {...a,...b};

b should override a or provide an error.

sacko87
  • 143
  • 1
  • 6
-1

Using spread

const a = {key1 : 'key1', key2 : 'key2'}
const b = {key1 : 'override a'}

console.log({ ...a, ...b })
H.B.
  • 166,899
  • 29
  • 327
  • 400