Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating javascript object property?

I have a structure like the following:

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

I was wondering how I would update these values ? i.e. I though the following was correct

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

but it's wrong ? How can I fix this ?

like image 403
Andy Avatar asked Feb 26 '12 16:02

Andy


2 Answers

Using ES7+ syntax and a functional approach:

const new_obj = { ...obj, name: { first: 'blah', last: 'ha'} } 
like image 111
Ramon Diogo Avatar answered Sep 17 '22 07:09

Ramon Diogo


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

like image 41
Vincent J Avatar answered Sep 18 '22 07:09

Vincent J