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?
CodePudding user response:
Use []
let person = { name: "Hilda", "id": 123, "phone": "000-000-0000" };
let roster = { [person.name] : person.phone };
console.log(roster)