Updating javascript object property?

后端 未结 8 1866
盖世英雄少女心
盖世英雄少女心 2021-02-01 03:26

I have a structure like the following:

skillet.person = {
  name: {
    first: \'\',
    last: \'\'
  }, 
  age: {
    current: \'\' 
  },
  birthday: {
    day:         


        
8条回答
  •  爱一瞬间的悲伤
    2021-02-01 03:45

    On recent browsers with ECMAScript 2015, you can do:

    Object.assign(skillet.person.name, { first: 'blah', last: 'ha'});
    

    which will preserve any existing attribute not listed in the right object.

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

    [EDIT] With ES7, you can do even shorter (but is it clearer?...):

    {...skillet.person.name, ...{ first: 'blah', last: 'ha'}};
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

提交回复
热议问题