6 Essential JavaScript Object Static Methods
Jenil
Posted on September 15, 2024
Just like a well-crafted movie script, JavaScript has key methods for handling objects that make coding a breeze.
Let’s dive into these essential Object static methods:
1. Object.create()
This method creates a new object with the specified prototype object and properties.
const movieObj = {
length: 2.4,
rating: 8.5
};
const movie1 = Object.create(movieObj);
movie1.name = 'Dunki';
// Dunki 2.4 8.5
console.log(movie1.name, movie1.length, movie1.rating);
const movie2 = Object.create(movieObj);
movie2.name = 'Salaar';
movie2.length = 2.52;
// Salaar 2.52 8.5
console.log(movie2.name, movie2.length, movie2.rating);
2. Object.assign()
This method is used to copy the values and properties from one or more source objects to a target object.
const target = { a: 10, b: 20 };
const source1 = { b: 12, c: 24 };
const source2 = { c: 29, d: 35 };
const returnedTarget = Object.assign(target, source1, source2);
// Output: { a: 10, b: 12, c: 29, d: 35 }
console.log(target);
// Output: { a: 10, b: 12, c: 29, d: 35 }
console.log(returnedTarget);
3. Object.keys()
This method returns the list of keys of object.
const movie = {
title: 'Dunki',
director: 'Rajkumar Hirani',
};
const keys = Object.keys(movie);
// Output: [ 'title', 'director' ]
console.log(keys);
4. Object.values()
This method returns the list of values of object.
const movie = {
title: 'Dunki',
director: 'Rajkumar Hirani',
};
const values = Object.values(movie);
// Output: [ 'Dunki', 'Rajkumar Hirani' ]
console.log(values);
5. Object.entries()
This method is used to get an array of key-value pairs from object.
const movie = {
title: 'Dunki',
director: 'Rajkumar Hirani',
};
const entries = Object.entries(movie);
// Output: [ [ 'title', 'Dunki' ], [ 'director', 'Rajkumar Hirani' ] ]
console.log(entries);
6. Object.fromEntries()
This method transforms a list of key-value pairs into an object.
const entries =
[ [ 'title', 'Dunki' ], [ 'director', 'Rajkumar Hirani' ] ];
const movieObj = Object.fromEntries(entries);
// Output: { title: 'Dunki', director: 'Rajkumar Hirani' }
console.log(movieObj);
With these JavaScript methods, you’re ready to direct your code like a pro! Enjoy crafting your code masterpieces! 🌟
Posted on September 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 30, 2024