2

The const person = { address } object property assignment that is equivalent to const x = { address: address }, and I'm well aware that is not possible to assign a property like this const person = { adress.street }, but what I want to know is the why behind the "you can't". Why javascript don't const person = { 'adress.street': address.street }. What javascript is doing behind the scenes?

6
  • ECMA-262 -> 12.2.6 Object Initializer Commented Feb 13, 2020 at 18:35
  • Actually you can (in the future, maybe) Commented Feb 13, 2020 at 18:43
  • @JonasWilms That's great! I'll add that link to my answer, if you don't have any objections. Commented Feb 13, 2020 at 18:44
  • @amy I don't own TC39, so ... ;) Commented Feb 13, 2020 at 18:45
  • 1
    @amy these are my internetpoints! Gimme tem back! :) Commented Feb 13, 2020 at 18:54

2 Answers 2

4

It's how its defined in the EcmaScript specification. This "shorthand property" syntax was introduced in ES2015.

An object literal is composed of a PropertyDefinitionList, which is itself defined in terms of PropertyDefinitions.

A property definition is defined as:

  • An identifier (this is the so-called "shorthand syntax" you're asking about)
  • Property name : Assignment expression
  • other things that aren't relevant to the question

In your question, adress.stree is not an identifier; it is an expression composed of two identifiers joined by a member access operator. Thus it does not fit the specification and cannot be used in the shorthand syntax.

A TC39 proposal exists to extend the syntax even further, giving you what you're looking for.

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

Comments

1

You can do with a function.

function setObjectProperty(object, property, value) {
  var props = property.split(".");
  var obj = object;
  for (let i = 0; i < props.length - 1; i++) {
    const prop = props[i];
    if (prop in obj && typeof obj[prop] == "object") {
      obj = obj[prop];
    } else {
      obj = obj[props[i]] = {};
    }
  }
  obj[props[props.length - 1]] = value;
}

//# Usage

const person = {};
setObjectProperty(person,"address.street","Fatih Sultan Mehmet Cad.");
setObjectProperty(person,"address.city","Konya");
setObjectProperty(person,"country.name","Türkiye");
setObjectProperty(person,"country.short","TR");
console.log(person);

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.