Ian Guimarães
Ian Guimarães

Reputation: 421

About javascript object property assignment

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?

Upvotes: 2

Views: 96

Answers (2)

Hasan Delibaş
Hasan Delibaş

Reputation: 500

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);

Upvotes: 1

user47589
user47589

Reputation:

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.

Upvotes: 4

Related Questions