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?

2
  • I would try something along the lines of ({...a, ...b}) where a and b are your two objects. Commented May 31, 2018 at 13:42
  • 3
    The ... construct is not an "operator". It's a syntactic element but not part of the expression grammar. Commented May 31, 2018 at 13:42

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.