Woodchuck
Woodchuck

Reputation: 4474

Destructuring JavaScript Object

I have a JavaSCript object, person, that contains id, name, phone and address properties. I want to modify the property names and put them into a new object, personData. Can this be done in 1 step?:

Step 1 (create a var for each property with different names):

var { id:personId, 
      name:personName, 
      phone:personPhone, 
      address:personAddress
   } = person;

Step 2 (create a new object containing those vars):

var personData = {
    personId,
    personName,
    personPhone,
    personAddress
}

Upvotes: 0

Views: 149

Answers (2)

holydragon
holydragon

Reputation: 6728

create a new object containing those vars:

var personData = {
    personId: person.id,
    personName: person.name,
    personPhone: person.phone,
    personAddress: person.addres
}

Upvotes: 1

Adrian Brand
Adrian Brand

Reputation: 21658

You want the spread operator, not destructuring.

var personData = { ...person, name: 'New name', phone: 'New phone' }

This creates a new object personData with all the properties of person and either adds or replaces the other properties listed.

Upvotes: 1

Related Questions