skip to Main Content

Say I have an object like the following:

myObject{
   name: '...',
   label: '...',
   menuSettings: {
      rightAlignment: true,
      colours: [...],
   },
}

I would like to change the rightAlignment value to be false. I’m having quite a bit of trouble trying to access and modify just this value, without having to rewrite the rest of the object. I tried myObject.find(…) which didn’t quite suit, and now was trying

Object.assign(this.myObject, {menuSettings: {rightAlignment: false}});

Which wasn’t working because I’m guessing I didn’t access the property correctly. Is there any way to cleanly do this?

3

Answers


  1. Just use the property accessor dot notation .:

    this.myObject.menuSettings.rightAlignment = false;
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#dot_notation

    Login or Signup to reply.
  2. You’re pretty close there. If I understand correctly, you want to merge an existing object with the latest value from another object. Which you can achieve by doing as;

    myObject.menuSettings = Object.assign({}, myObject.menuSettings, { rightAlignment: false });
    

    The way you’re doing currently, is not wrong though. but you’re replacing the entire menuSettings which then will remove your menuSettings.colours.

    Or just access the property directly as per answer by Alexander.

    var myObject = {
       name: '...',
       label: '...',
       menuSettings: {
          rightAlignment: true,
          colours: ['...'],
       },
    }
    
    myObject.menuSettings = Object.assign({}, myObject.menuSettings, { rightAlignment: false });
    
    console.log(myObject)
    Login or Signup to reply.
  3. You can update the rightAlignment property within menuSettings without rewriting the entire object. Here’s one way to achieve this using the spread syntax (…)

    let myObject = {
       name: '...',
       label: '...',
       menuSettings: {
          rightAlignment: true,
          colours: [],
       },
    };
    
    //update rightAlignment property
    myObject = {
      ...myObject,
      menuSettings: {
        ...myObject.menuSettings,
        rightAlignment: false,
      },
    };
    
    console.log(myObject);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search