0

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.

3 Answers3

1

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 1
    Thanks so much De! I didn't know that the spread was multi-level object specific also, learned something new! –  Mar 25 '21 at 13:12
  • @DevSem You are more than welcome, I'm glad I was able to help. – DecPK Mar 25 '21 at 13:16
0

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)
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

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.

Christian
  • 6,961
  • 10
  • 54
  • 82
  • 1
    Thanks a bunch Christian! Learned that the spreader can be used on inner objects and not just the parent, good learning curve this morning. –  Mar 25 '21 at 13:12