Find number of properties in an object
var student = {
name: "Anurag Nayak",
empId: "123",
1: "test",
nestedObj: {
id: 123,
nestedObj1: {
nestedObj2: {
nestedObj3: {
nestedObj4: {},
},
},
},
},
testFunc2: function () {
console.log(2);
},
testFunc3: () => {
console.log(3);
},
};
//1.calculate property length -->6
Object.keys(student).length;
Find the depth of nestedObj inside the student array
//2.Find the nested object depth :->nestedObj --> length
//Object.values(nestedObj).forEach((v) => will loop on values
//typeof v ==> to determine if its object or not
//v==>{nestedObj2: {…}} {nestedObj3: {…}} {nestedObj4: {…}}
var student = {
name: "Anurag Nayak",
empId: "123",
1: "test",
nestedObj: {
id: 123,
nestedObj1: {
nestedObj2: {
nestedObj3: {
nestedObj4: {},
},
},
},
},
testFunc2: function () {
console.log(2);
},
testFunc3: () => {
console.log(3);
},
};
let depth = 0;
let depthOfNestedObject = (nestedObj) => {
Object.values(nestedObj).forEach((v) => {
if (typeof v === "object") {
depth++;
depthOfNestedObject(v);
}
});
};
depthOfNestedObject(student.nestedObj);
console.log(`%c ${depth}`, "color:red;font-size:20px");
//output :- 4
find all the functions in the same object
var student = {
name: "Anurag Nayak",
empId: "123",
1: "test",
nestedObj: {
id: 123,
nestedObj1: {
nestedObj2: {
nestedObj3: {
nestedObj4: {},
},
},
},
},
testFunc2: function () {
console.log(2);
},
testFunc3: () => {
console.log(3);
},
};
Object.values(student).forEach((v) => {
if (typeof v === "function") console.log(v);
});
comibinations of the string
//input string -test
//output should be --> ['t','te','tes','test','e','es','est','s','st','t']
let combinations = (str) => {
var final = [];
for (var i = 0; i < str.length; i++) {
for (var j = i + 1; j < str.length + 1; j++) {
final.push(str.slice(i, j));
}
}
return final;
};
console.log(combinations("test"));
/*Explanations
As you know in slice -->last index is exclusive and first index is inclusive
so it will exclude the last index ..
so for example
"test".slice(0,1) ==>t
0th index will be included -->t
1st index is excluded --> e is excluded ...
******ITERATIONS**
i=0,j=1 to 4
"test".slice(0,1) ==>t
"test".slice(0,2) ==>te
"test".slice(0,3) ==>tes
"test".slice(0,4) ==>test
i=1,j=2 to 4
"test".slice(1,2) ==>e
"test".slice(1,3) ==>es
"test".slice(1,4) ==>est
i=2,j=3 to 4
"test".slice(2,3) ==>s
"test".slice(2,4) ==>st
i=3,j=4 to 4
"test".slice(3,4) ==>t
*/
Extension method to captialize the first letter of string
String.prototype.CapitalizeFirstLetter = function () {
return this[0].toUpperCase() + this.substring(1);
};
console.log("test".CapitalizeFirstLetter());
//Output:- Test