Values in an object can be another object:
Example
name:"John",
age:30,
cars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
You can access nested objects using the dot notation or the bracket notation:
Example
or:
Example
or:
Example
or:
Example
let p2 = "car2";
myObj[p1][p2];
Nested Arrays and Objects
Values in objects can be arrays, and values in arrays can be objects:
Example
name: "John",
age: 30,
cars: [
{name:"Ford", "models":["Fiesta", "Focus", "Mustang"]},
{name:"BMW", "models":["320", "X3", "X5"]},
{name:"Fiat", "models":["500", "Panda"]}
]
}
To access arrays inside arrays, use a for-in loop for each array:
Example
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
Property Attributes
All properties have a name. In addition they also have a value.
The value is one of the property's attributes.
Other attributes are: enumerable, configurable, and writable.
These attributes define how the property can be accessed (is it readable?, is it writable?)
In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
Prototype Properties
JavaScript objects inherit the properties of their prototype.
The delete
keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.
Practice Excercise Practice now