0

I have this function.

function foo(newdata) { 
     utils.method('GET', '/auth', {
        response: {
          data: {
            settings: {
              last_email_notification_shown_date: new Date(),
              email_notifications: null,
            }
            ...newdata
          }
        }
      });
 }

But every time I want to update the 'settings' property, I have to pass all of it to data:

foo(settings {
   last_email_notification_shown_date: new Date(),
   email_notifications: null,
   SomeNewProperty: 'whatever'
})

Is there a way to update the 'settings' property in this function without the need to rewrite it whole? I just want to update the property, not to override it.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Does `foo` have access to the existing settings? Also note that your second code block has a syntax error which makes it hard to tell what you're really doing. – T.J. Crowder Apr 12 '19 at 10:37
  • 2
    (Side note: `...` isn't an operator, it's primary syntax; it can't be an operator because it doesn't have a single result value. Doesn't really matter much. :-) But if it were an operator, it wouldn't do different things in different situations [spread vs. rest] and you could use it anywhere. But you can only use spread and rest in specific places where that syntax is defined.) – T.J. Crowder Apr 12 '19 at 10:38

1 Answers1

0

Is there a way to update the 'settings' property in this function without the need to rewrite it whole?

It's hard to tell from your question quite what you're really doing, but if the goal is to add newdata to the existing settings, you're just spreading it in the wrong place:

function foo(newdata) { 
     utils.method('GET', '/auth', {
        response: {
          data: {
            settings: {
              last_email_notification_shown_date: new Date(),
              email_notifications: null,
              ...newdata // <============================ moved
            }
          }
        }
      });
}

then

foo({
   SomeNewProperty: 'whatever'
});

If you need to call foo with an object with things outside settings and also within settings, then it gets slightly more complicated, but not a lot:

function foo(newdata) { 
     utils.method('GET', '/auth', {
        response: {
          data: {
            ...newdata,                     // <========================
            settings: {
              last_email_notification_shown_date: new Date(),
              email_notifications: null,
              ...newdata.settings           // <========================
            },
          }
        }
      });
}

then

foo({
    settings: {
       SomeNewProperty: 'whatever'
    },
    otherStuff: "foo"
});

That spreads newdata (including settings), but then overwrites newdata's settings in the new object with a replacement settings, in which we spread newdata.settings.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875