Sometimes most of us get confused while dealing with Arrays and Objects. This leads into further confusions when choosing which manipulation technique to use. For example, we can find the length only if we know whether it is an array or an object. As both have different approaches.
This is a basic checklist for all the programmers coding out there. So, in this blog you will learn how to differentiate between Arrays and Objects.
What are Arrays?
Array items are accessed using indices
Format [ , , , ]
Example [1, 2, 3, 4, 5]
Arrays can contain objects, strings, numbers, arrays & boolean.
Initialization
1. _datatype_[] = [, , ,];
2. Array\<_datatype_\> = [, , ,]; // _Uses a generic array type_
Array of objects
Syntax :
[{“ “:” “,” “:” “},{“ “:” “,” “:” “}]
Example:
[
{ “position”: “winner”,”country”: “U.S.A” },
{ “position”: “runner”,”country”: “China” }
];
[
{ “rainy”: true,”sunny”: false },
{ “rainy”: false,”sunny”: true }
]
Array of strings
Example:
[‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,’Friday’, ‘Saturday’];
[‘a’, ‘b’, ‘c’, ‘d’];
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ’6’, ‘7’];
Array of numbers
Example:
[1, 2, 3, 4, 5];
[788.34, 432.34, 3234.72];
Array of arrays
These can be otherwise called as multi-dimensional arrays.
[
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7]
];
Array of booleans
[true, false, false, true]
What are Objects?
An object is a collection of properties, and a property is an association between a name (or key) and a value. A property’s value can be a function, in which case the property is known as a method.
Object properties are accessed using keys.
Keys must be strings, and values must be a valid JSON data type (string, number, object , array, boolean or null).
Format { “ ”: “ ” }
Example {“position”: “winner”,”country”: “U.S.A”}
Object of arrays and objects
{
“binary”: [{“id”:1,”name”:0},{“id”:2,”name”:1}],
“boolean”: [{“id”:1,”value”: false},{“id”:2,”value”: true}]
}
Nested Objects:
“results”: {
“tennis”: [
{“position”: “winner”,“country”: “U.S.A},
{“position”: “runner”,“country”: “China”}
]
}
Object of objects
JSON Objects are enclosed within {}
“universe”: {
“planets”: {
“day”: “Sun”,
“night”: “Moon”
}
}
Nested JSON Object:
json: any = {
"visible": true,
"colors": {
"data": {
"darkest": "Black",
"lightest": "white",
"neutral": "Grey",
"spectrum": {
"1": "Violet",
"2": "Indigo",
"3": "Blue",
"4": "Green",
"5": "Yellow",
"6": "Orange",
"7": "Red"
},
"default": "Grey",
"primary": "Blue",
"danger": "Red",
"warning": "Yellow",
"success": "Green",
"RGB": {
"r": "Red",
"g": "Green",
"b": "Blue"
}
}
}
}
So these are the differences between Arrays and Objects. I hope that from now you all can use these types without any worries.
Happy coding :)
Top comments (0)