Objects

An object is an unordered collection of data. Values in an object are stored as key-value pairs. You can create an object by declaring a comma-separated list of key:value pairs within curly braces, or simply a pair of opening-closing curly braces if you want to start with an empty object:

const color = {name: "red", code: ff0000};
const empty = {};

Objects can contain other objects and arrays, which can also contain objects. They can also contain functions, which have access to local properties and behave as methods:

const city = {name: "Sao Paulo",
location: {latitude: 23.555, longitude: 46.63},
airports: ["SAO","CGH","GRU","VCP"]};
const circle = {
x: 200,
y: 100,
r: 50,
area: function() {
return this.r * this.r * 3.14;
}
}

A typical dataset used by a simple chart usually consists of an array of objects:

var array2 = [
{continent: "Asia", areakm2: 43820000},
{continent: "Europe", areakm2: 10180000},
{continent: "Africa", areakm2: 30370000},
{continent: "South America", areakm2: 17840000},
{continent: "Oceania", areakm2: 9008500},
{continent: "North America", areakm2=24490000}
];

You can access the properties of an object using the dot operator or brackets containing the key as a string. You can run its methods using the dot operator:

const latitude = city.location.latitude;
const oceania = array2[4].continent;
const code = color["code"];
circle.r = 100;
const area = circle.area();

You can also loop over the properties of an object:

for(let key in color) {
console.log(key + ": " + color[key]);
}

Properties and functions can be added to objects. It's common to write code that declares an empty object in a global context so that operations in other contexts add data to it:

const map = {};
function getCoords(coords) {
map.latitude = coords.lat;
map.longitude = coords.lng;
}

Objects can also be created with a constructor. You can create an object that contains the current date/time using:

const now = new Date();

A Chart.js instance is created using a constructor that receives at least two parameters. The second parameter is an object with two properties, a string and another object:

const chart =
new Chart("bar-chart ",{type:"bar", data:{labels:[],datasets:[]}});

JSON is a data format based on JavaScript objects. It has the same structure as a JavaScript object, but the property keys have to be placed within double quotes:

{"name": "Sao Paulo",
"location": {"latitude": 23.555, "longitude": 46.63},
"airports": ["SAO","CGH","GRU","VCP"]};

To use a JSON string in JavaScript you have to parse it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset