Skip to content

Commit 1275895

Browse files
authored
Update objects.js
1 parent aa48b22 commit 1275895

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

03-DataStructures/objects.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,65 @@
1111
// 8. Describing the structure and metadata of a JSON object for data serialization and deserialization.
1212
// 9. Storing temporary data in a client-side web application using the window.localStorage object.
1313
// 10. Using objects as a data store for simple key-value databases, such as IndexedDB or WebSQL in the browser.
14+
15+
16+
17+
// Traversal Object
18+
19+
20+
//Example 1: Using for...in loop to traverse an object (Basic)
21+
const obj = {
22+
firstName: 'John',
23+
lastName: 'Doe',
24+
age: 30,
25+
};
26+
27+
for (const key in obj) {
28+
if (Object.hasOwnProperty.call(obj, key)) {
29+
console.log(`${key}: ${obj[key]}`);
30+
}
31+
}
32+
33+
// Example 2: Using Object.keys() and forEach() to traverse an object (Intermediate)
34+
Object.keys(obj).forEach((key) => {
35+
console.log(`${key}: ${obj[key]}`);
36+
});
37+
38+
// Example 3: Recursively traversing a nested object with depth (Expert)
39+
const obj2 = {
40+
name: {
41+
firstName: 'John',
42+
lastName: 'Doe',
43+
},
44+
age: 30,
45+
address: {
46+
street: '123 Main St',
47+
city: 'New York',
48+
country: {
49+
name: 'United States',
50+
code: 'US',
51+
},
52+
},
53+
};
54+
55+
function traverseObject(obj, prefix = '') {
56+
for (const key in obj) {
57+
if (Object.hasOwnProperty.call(obj, key)) {
58+
const newKey = prefix ? `${prefix}.${key}` : key;
59+
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
60+
traverseObject(obj[key], newKey);
61+
} else {
62+
console.log(`${newKey}: ${obj[key]}`);
63+
}
64+
}
65+
}
66+
}
67+
68+
traverseObject(obj2);
69+
/**************************
70+
In this expert example, we define a traverseObject function that takes an object and an optional prefix string as arguments.
71+
It then iterates through the object's keys and checks if the corresponding value is an object itself (excluding arrays).
72+
If it is, the function calls itself recursively with the nested object and the current key appended to the prefix.
73+
If it's not an object, it logs the key and value with the accumulated prefix.
74+
This will traverse an object of any depth and log the keys and values with their full path in the object hierarchy.
75+
***************************/

0 commit comments

Comments
 (0)