简体   繁体   中英

JavaScript: Add Key and Value to Object Using ES6 {} Shortcut

I have the following object:

obj = {name: 'Amy',
       age: 36,
       type: 'sanguine'}

I want to add another key and value to the above object, but I specifically want to do that using the {} shortcut.

This is an example of using the {} shortcut:

function test (bloodtype) {
  return { bloodtype }
}

test('A')

Result: { index: 0, elem: 22 }

But trying to add bloodtype to obj using that shortcut doesn't work.

function test (bloodtype) {
      return obj{ bloodtype }
}

test('A')

Error:

evalmachine.<anonymous>:31
  return obj{ bloodtype }
            ^
SyntaxError: Unexpected token {

What am I doing wrong?

To use the shortcut syntax, you first need to use the object spread and then merge it with your new property:

function test (obj, bloodtype) {
  return {...obj, bloodtype};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM