Today, new languages are being created to build a new level of applications that have advanced features and also meet demanding needs of businesses and users.
New programming languages don’t always bring forward big changes. There are many powerful languages that always are around. Among them JavaScript that is always in the list of popular programming languages and developers and industry leads are falling in love with it all the time using it everywhere on the web, mobile, server and even on IoT.
Following are the tricks of object in javascript. These are very important for interview.
var arr = [1,2,3,4]
var obj = { a:1, b:2 };
var length = Object.keys(obj).length;
console.log(obj.lengt); // undefined
console.log(length) ; // 2
var username = {
firstName: "aman",
lastName:"tiwari"
};
//First approach
for(let u in username){
if(username.hasOwnProperty(u)){
console.log(u,username[u]);
}
}
/* outcome will be
firstName aman
lastName tiwari*/
//Second approach
for(let u in Object.keys(username)){
console.log(u, username[u]);
}
/*outcome will be
firstName aman
lastName tiwari*/
//Third approach
Object.entries(username).forEach(([key,value]) => console.log(key, value));
/*outcome will be
firstName aman
lastName tiwari*/
var person = { name: "aman", age:"20"}
var arr =[];
//First approach
Object.keys(person).forEach(key => arr.push([key, person[key]]));
console.log(arr) // [['name', 'aman'], ['age', 20]]
//Second approach
var result = Object.keys(person).map(key => [key, person[key]])
console.log(result) // [['name', 'aman'], ['age', 20]]
//third approach
console.log(Object.entries(person));// [['name', 'aman'], ['age', 20]]
var user = {
name: "aman",
address: {
street: "Hauz khas Enclave",
city: "New Delhi"
}
}
var property = 'name' in user;
console.log(property) //true
var defaultUser = {
name:"",
email:"",
subscribe:true
}
var actualUser = {
name: "Aman",
email:"[email protected]"
}
var userData = Object.assign(defaultUser, actualUser);
console.log(userData); // { name: "Aman", email:"[email protected]", subscribe:true}
var filterObj ={}
var name = { name: 'aman' , age: "20"}
const result = Object.keys(name)
.filter(key => key !=='name')
.map(key => filterObj[key]=name[key]);
console.log(filterObj) //{ age: 20 }
var name = {
firstName: "aman",
lastName:"tiwari",
age: "20",
}
var values = Object.keys(name).map(key => name[key]);
console.log(values); // ['aman', 'tiwari', '40']
P.S - reach out to me incase you have doubts