0

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
}

2 Answers 2

1

create a new object containing those vars:

var personData = {
    personId: person.id,
    personName: person.name,
    personPhone: person.phone,
    personAddress: person.addres
}
Sign up to request clarification or add additional context in comments.

3 Comments

holydragon, your Step 2 is what I was looking for. Your Step 1 seems superfluous, though. Thanks!
If the answer solves your problem, please consider accepting it. Thank you.
holydragon, see my comment. Step 2 answers my question. Can you edit and remove step 1? Then I can accept. Thanks.
1

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.

1 Comment

This seems promising. However, it seems to allow you to change the property values when creating that new object and/or to add new properties. Is there a way to actually remove an existing property (either by changing its name or removing it and adding a different one)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.