0

I have the following object:

var inv = {roles: {"xxx00": {roleId: "zzzz33"}}, assign: [1, 2, 3] }

This is the result:

{ roles: { "1234": {roleId: null}, "5678": {roleId: null}}}

I need to consolidate the object with this result:

{roles: {"1234": {roleId: null}, "5678": {roleId: null}, "xxx00": {roleId: "zzzz33"}}, assign: [1, 2, 3] }

And I need to get that with the spread syntax

Any idea how the syntax should be to get this result without losing the original roleId?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Leonardo Uribe
  • 123
  • 1
  • 13
  • I would try something along the lines of `({...a, ...b})` where `a` and `b` are your two objects. – Yoric May 31 '18 at 13:42
  • 3
    The `...` construct is *not* an "operator". It's a syntactic element but not part of the expression grammar. – Pointy May 31 '18 at 13:42

2 Answers2

2

Below are two examples one with no object mutation, the other with.

let inv = {roles: {"xxx00": {roleId: "zzzz33"}}, assign: [1, 2, 3] };
let res = { roles: { "1234": {roleId: null}, "5678": {roleId: null}}};

// create new object to spec, no mutation.
let combine = { roles: { ...inv.roles, ...res.roles, }, assign: [ ...inv.assign ] };
console.log(combine);

// mutate original object.
console.log(inv);
inv.roles = {  ...inv.roles, ...res.roles, };
console.log(inv);
D Lowther
  • 1,609
  • 1
  • 9
  • 16
1

just do this

const consolidated = {...inv, roles: {...inv.roles, ...result.roles} };

Assuming you only want to merge your result roles with the inv var roles, this will create consolidated based on inv but with result roles merged in inv roles.