Reputation: 421
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
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
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 PropertyDefinition
s.
A property definition is defined as:
:
Assignment expressionIn 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