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?
-
ECMA-262 -> 12.2.6 Object InitializerAndreas– Andreas2020-02-13 18:35:49 +00:00Commented Feb 13, 2020 at 18:35
-
Actually you can (in the future, maybe)Jonas Wilms– Jonas Wilms2020-02-13 18:43:54 +00:00Commented 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.user47589– user475892020-02-13 18:44:29 +00:00Commented Feb 13, 2020 at 18:44
-
@amy I don't own TC39, so ... ;)Jonas Wilms– Jonas Wilms2020-02-13 18:45:15 +00:00Commented Feb 13, 2020 at 18:45
-
1@amy these are my internetpoints! Gimme tem back! :)Jonas Wilms– Jonas Wilms2020-02-13 18:54:08 +00:00Commented Feb 13, 2020 at 18:54
2 Answers
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.
Comments
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);