Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Set a Javascript Object Key to Be Another Object's Value

I have an Javascript object called person with various properties such as id, name, phone, etc.

I want to create a new Javascript object called roster that is just the name. Something like this:

let person = { name: "Hilda", "id": 123, "phone": 000-000-0000 };
let roster = { person.name : person.phone };

However, React throws an error having person.name in the key. It doesn’t matter if I do person.name or person["name"]. I have to do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let roster = {};
roster[person.name] = person.phone;

Is there some special syntax to allow person.name to be set as the key directly, or is the work-around required?

>Solution :

Use []

let person = { name: "Hilda", "id": 123, "phone": "000-000-0000" };
let roster = { [person.name] : person.phone };

console.log(roster)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading