user12394904
user12394904

Reputation:

Changing the value of a parameter based on spread operator

So let's say that I have an object literal, which is the following:

let test = {
  settings: {
    title: '',
    has_content: true,
    can_edit: false,
  }
}

Now I have another object literal as shown below:

let test2 = {
  ...test,
  settings: {
    can_edit: true,
  }
}

How can I bring over all the parameters from the test object literal but have the ability to change values in test2?

So ultimately, I'd like for this:

let test2 = {
    settings: {
      title: '', (This is default)
      can_edit: true, (This value is changed)
      has_content: true, (This is default)
    }
}

Now, when I console.log test2, all that I see in the settings is the can_edit: true, but not the title or has_content.

Upvotes: 0

Views: 509

Answers (3)

Christian
Christian

Reputation: 7429

It should be like this

let test2 = {
   ...test,
   settings: {
     ...test.settings,
     can_edit: true,
   }
}

Explanation: You need to spread object by object. Be aware, if you use the spread before changing the values (like I did) your changes survive.

Upvotes: 0

DecPK
DecPK

Reputation: 25408

You need to spread the test.settings in test2.settings to merge the properties and override with the latest one that are defined in test2.settings.

let test = {
  settings: {
    title: "",
    has_content: true,
    can_edit: false,
  },
};

let test2 = {
  settings: {
    ...test.settings,
    can_edit: true,
  },
};

console.log(test2);

Upvotes: 1

prasanth
prasanth

Reputation: 22490

Because you test.settings key will be replaced by test2.settings. so you should spread the test.setting into test2.settings like below

let test = {
  settings: {
    title: '',
    has_content: true,
    can_edit: false,
  }
}

let test2 = {
  settings: {
    ...test.settings,
    can_edit: true,
  }
}
   
console.log(test2)

Upvotes: 0

Related Questions