Javascript object methods
Created By: chatGPT
In JavaScript, objects are collections of properties, and each property is a key-value pair. Objects come with several built-in methods that you can use to manipulate these key-value pairs. Here are some important methods:By understanding these object methods, you can manipulate and interact with JavaScript objects more effectively.
Object.keys()
: This method returns an array of a given object's own enumerable property names.const person = { name: 'Alice', age: 25, city: 'New York' };
const keys = Object.keys(person);
console.log(keys); // ['name', 'age', 'city']
Object.values()
: This method returns an array of a given object's own enumerable property values.const values = Object.values(person);
console.log(values); // ['Alice', 25, 'New York']
Object.entries()
: This method returns an array of a given object's own enumerable property [key, value]
pairs.const entries = Object.entries(person);
console.log(entries); // [['name', 'Alice'], ['age', 25], ['city', 'New York']]
Object.assign()
: This method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.const target = { fruit: 'apple' };
const source = { vegetable: 'carrot', dairy: 'milk' };
const result = Object.assign(target, source);
console.log(result); // { fruit: 'apple', vegetable: 'carrot', dairy: 'milk' }
Object.freeze()
: This method freezes an object, preventing new properties from being added to it and marking all existing properties as read-only.const obj = { prop: 42 };
Object.freeze(obj);
obj.prop = 33; // No change
console.log(obj.prop); // 42
Object.seal()
: This method seals an object, preventing new properties from being added but allowing existing properties to be modified.const obj = { prop: 42 };
Object.seal(obj);
obj.prop = 33;
console.log(obj.prop); // 33
obj.newProp = 'new'; // No change
console.log(obj.newProp); // undefined
Object.prototype.hasOwnProperty()
: This method returns a boolean indicating whether an object has the specified property as its own property (as opposed to inheriting it).const obj = { name: 'Bob' };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('age')); // false