0

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?

2 Answers 2

1

Use []

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

console.log(roster)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I've not seen array brackets used that way before. What is their syntactical significance?
Hi @Elliptica, I agree it feels a bit odd, but the idea is that's how you read the value Object[key], so that's how you set the key as well { [computedKey] : "abc"}. This is called a computed property name
1

Vugar's answer is correct, this can be done by placing brackets [] around the first object's property name.

This is called a computed property name. From the MDN web docs:

The object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.

Now you can use a similar syntax in object literals, too:

// Computed property names
let i = 0;
const a = {
  [`foo${++i}`]: i,
  [`foo${++i}`]: i,
  [`foo${++i}`]: i,
};

console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3

const items = ["A", "B", "C"];
const obj = {
  [items]: "Hello",
};
console.log(obj); // A,B,C: "Hello"
console.log(obj["A,B,C"]); // "Hello"

const param = 'size';
const config = {
  [param]: 12,
  [`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,
};

console.log(config); // {size: 12, mobileSize: 4}

MDN Docs Reference

Comments

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.