Skip to content
Advertisement

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:

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?

Advertisement

Answer

Use []

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

console.log(roster)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement