Updating javascript object property?

后端 未结 8 1863
盖世英雄少女心
盖世英雄少女心 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:52

    As @ramon-diogo wrote with ES7+

    I like to update nested values like:

    let user = {
        name: {
            first: 'john',
            last: 'smith'
        },
        age: 18,
        city: 'new york'
    }
    
    const age = 20;
    
    user = {...user, age}
    
    console.log(user.age)
    // output: 20
    
    
    const newData ={
        age: 22,
        city: 'san francisco'
    };
    
    user = {...user,...newData}
    
    console.log(user.name.first)
    // output: john
    console.log(user.age)
    // output: 22
    console.log(user.city)
    // output: 'san francisco'
    

提交回复
热议问题