Know how you can use a Javascript object and its props.
Javascript objects have properties or props. As you would have seen in the post about objects and primitives, object operations are quite easy. Though objects can mean more than a few things in Javascript, we will limit discussion of an object to the ** real real ** object.
..i.e.,
You should know a few things about this object to make your life much easier.
Get object props
Here’s a simple object from the previous post.
1
|
let apple = { color: "red" };
|
Access the prop of the object -
1
|
console.log("color of the apple is: ", apple["color"]);
|
Or, you can use dot notation.
1
|
console.log("color of the apple is: ", apple.color);
|
Both of the above notations have the same end result, but for one major behaviour when props do not exist.
1
2
3
4
5
6
|
// shape is not defined yet
console.log("apple shape: ", apple["shape"]); // undefined
//do not use if you are not sure whether prop exists
// results in error (depends on environment)
console.log("apple shape: ", apple.shape);
|
If you have a space or special character in the prop (i.e., does not follow Javascript variable naming / identifier rules), you must use the bracket notation.
1
2
3
4
5
6
7
8
|
let apple = { "1800number": "1-800-APPLE", size: "large" };
console.log("apple sweetness: ", apple["sweetness index"]); // undefined
// throws error, invalid identifier. program breaks
console.log("apple number", apple.1800number);
// undefined. program continues to run
console.log("apple number", apple['1800number']);
|
The default way of the coder(tm) is to use the bracket option when prop name/existence is not in one’s control, and use dot notation for its beauty.
When is the prop not in your control? Well, it turns out in many real-world cases. For example, if you are receiving parameters from other programs or from external systems.
The typical way of managing such unknown prop is to check for prop and assign default value.
1
2
3
4
5
6
7
|
let apple = { "1800number": "1-800-APPLE", size: "large" };
console.log("apple size: ", apple["size"] ? apple["size"] : "medium");
// OR
console.log("apple size: ", apple["size"] || "medium");
|
The variable checks go deeper in the rabbit hole as you will have props, props of props (= child objects), and so on.
1
2
3
4
|
let apple = { color: "red", size: "large", price: { USD: 1, EUR: 2 } };
console.log("apple price", apple["price"]["USD"]); // 1
console.log("apple price", apple.price["USD"]); // also 1
|
As you can see from the above example, it is perfectly valid to use dot, brackets, or both.
Set object props
Similar to getting values of objects, you will use bracket notation when setting value if you are not sure whether the prop exists (which is the typical case).
1
2
3
4
5
6
|
let apple = { color: "red", size: "large", price: { USD: 1, EUR: 2 } };
console.log("apple price (USD)", apple["price"]["USD"]); // 1
apple.price["USD"] = 2;
console.log("apple price (USD)", apple["price"]["USD"]); // 2
|
You can also use variables instead of hardcoded props, in which case bracket notation is the only choice. Dot notation will check for a prop named ‘currency’ instead of treat it as a variable.
1
2
3
4
5
6
|
let country = "USA";
let apple = { color: "red", size: "large", price: { USD: 1, EUR: 2 } };
if (country == "USA") var currency = "USD";
console.log("apple price", apple.price[currency]); // 1
|
Accessing all/individual props of an object
You would have accessed array elements by cycling through them till you hit ‘stop’ sign provided by the .length
prop.
You could do the same with generic objects with Object
.
1
2
3
|
let apple = { color: "red", size: "large" };
console.log("apple length: ", apple.length); // undefined
console.log("apple length: ", Object.keys(apple).length); // 2
|
Cycle through objects in a loop.
1
2
3
4
5
6
7
8
9
10
11
|
let apple = { color: "red", size: "large" };
for (let i = 0; i < Object.keys(apple).length; i++) {
console.log(
"prop:" + Object.keys(apple)[i] + "; val: " + apple[Object.keys(apple)[i]]
);
}
/*
Output:
prop:color; val: red
prop:size; val: large
*/
|
Alternatively, use modern Javascript.
1
2
3
4
5
6
7
8
|
Object.keys(apple).forEach((prop) => {
console.log("prop: " + prop + "; val: " + apple[prop]);
});
/* Output:
prop: color; val: red
prop: size; val: large
*/
|
Deleting object prop
Deleting a prop is as simple as using a delete statement.
1
2
3
4
5
|
let apple = { color: "red", size: "large" };
console.log("apple: ", apple); // apple: { color: 'red', size: 'large' }
delete apple["color"];
console.log("apple: ", apple); // apple: { size: 'large' }
|
Copying object props
Objects can be copied directly similar to any other variable.
1
2
3
4
|
let apple = { color: "red", size: "large" };
let orange = apple;
console.log("orange: ", orange); // { color: 'red', size: 'large' }
|
Due to the way Javascript handles variables and memory allocated to variables, copying an object just creates another variable pointing to the same memory location as the original variable.
1
2
3
4
5
6
7
8
|
let apple = { color: "red", size: "large" };
let orange = apple;
console.log("orange: ", orange); // { color: 'red', size: 'large' }
apple["color"] = "green";
console.log("apple: ", apple); // { color: 'green', size: 'large' }
console.log("orange: ", orange); // { color: 'green', size: 'large' }
|
However, deleting apple does not ‘delete’ orange. This is an important distinction of how Javascript works, and this is applicable to all variables.
1
2
3
4
5
6
7
|
let apple = { color: "red", size: "large" };
let orange = apple;
console.log("orange: ", orange); // { color: 'red', size: 'large' }
apple = null;
console.log("orange: ", orange); // { color: 'red', size: 'large' } - no change
|
If you want to truly clone the object, use a loop.
1
2
3
4
5
|
const orange = {};
for (let i = 0; i < Object.keys(apple).length; i++) {
orange[Object.keys(apple)[i]] = apple[Object.keys(apple)[i]];
}
console.log("orange: ", orange); // { color: 'red', size: 'large' }
|
When the object is cloned in the above fashion, it no longer shares the same variable value.
1
2
3
4
|
//.. same as above code
apple["color"] = "green";
console.log("orange: ", orange); // { color: 'red', size: 'large' } - no change
|
Finis
Javascript object is super friendly once you get to know it better.