Reputation: 803
I am learning javascript and was trying few basic examples. I found some strange behavior and thought this forum would help me in understanding the solution better.
I have created an object as below:
var school={
name:"purnapramati",
location:"girinagar",
'state-name':"karnataka",
proximity:true
}
Now, I add a property dynamically like below:
school.country="india";
When is print the school object, I see the updated country attribute with India as value.
Now, I try to add a property to proximity attribute:
school.proximity.distance="less than 4kms";
This time the distance attribute is not added to the proximity attribute and not reflected in the school object too.
Why is this behavior? Please explain me. I know this is a very basic question but I am looking for a convincing answer/justification.
Upvotes: 2
Views: 38
Reputation: 2173
The issue is that your proximity
property is not an object, so it cannot have attributes. It is a boolean with a single value.
I'm not sure what proximity
being true
represents, but you could do something like:
var school={
name:"purnapramati",
location:"girinagar",
'state-name':"karnataka",
proximity: {
nearby: true
}
}
after which you could give it additional properties as you are trying with distance
.
Or using your original structure you could do something like:
school.proximity = { distance: "less than 4kms" };
But then you will lose that true
value unless you store it in another attribute.
Upvotes: 4