-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisEmptyObject.js
More file actions
119 lines (84 loc) · 2.02 KB
/
isEmptyObject.js
File metadata and controls
119 lines (84 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// 1. Write a function to check it an Object is empty or not
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
console.log(isEmpty({}));
console.log(isEmpty({ 1: 2 }));
// 2. Merge two Objects
function merageObj(obj1, obj2) {
return { ...obj1, ...obj2 };
}
console.log(merageObj({ a: 1, b: 2 }, { c: 3, d: 4 }));
// 3. clone an object (Shallow copy)
function shallowCopy(obj) {
return { ...obj };
}
const original = {
a: 1,
b: 2,
};
const copy = shallowCopy(original);
console.log(copy);
console.log(copy === original);
// 4. Deep clone an object(Deep Copy)
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
const originalDeep = {
a: 1,
b: {
c: 2,
},
};
const originalDeepCopy = deepCopy(originalDeep);
originalDeepCopy.b.c = 3;
console.log(originalDeep);
console.log(originalDeepCopy);
// 5. Count the properties in an Object
function countPropertiesInObj(obj) {
return Object.keys(obj).length;
}
console.log(
countPropertiesInObj({
a: 1,
b: {
c: 2,
},
})
);
// 6. Get keys and values as separated arrays
const person = {
name: "Arun",
age: 26,
city: "Hyderabad"
}
const keys = Object.keys(person);
const values = Object.values(person);
console.log("Keys: ", keys);
console.log("Values: ", values);
// 7. Check if an object has a properties
function checkObjectHasProperties(obj, key){
return obj.hasOwnProperty(key);
}
console.log(checkObjectHasProperties({a: 1, b: 2}, "3")); // false
console.log(checkObjectHasProperties({a: 1, b: 2}, "b")); // True
// 8. Convert Object to array of [key, value] pairs
function convertObjectIntoArray(obj){
return Object.entries(obj)
}
console.log(convertObjectIntoArray({a: 1, b: 2, c: 3}))
// 9. Get all the methods of an objects
function getAllMehtods(obj) {
return Object.keys(obj).filter(key => typeof obj[key] === "function")
}
const objWithMethods ={
a:1,
b: 2,
foo(){
return "Foo"
},
bar(){
return "bar"
}
}
console.log(getAllMehtods(objWithMethods))