DEV Community

muthu raja
muthu raja

Posted on

Understanding Key Object Methods in JavaScript

JavaScript’s Object comes packed with a number of useful methods that help developers manipulate objects with ease. Let’s walk through some of the most important ones, with brief explanations and examples

  1. Object.create()
  2. Object.assign()
  3. Object.keys()
  4. Object.values()
  5. Object.entries()
  6. Object.freeze()
  7. Object.seal()
  8. Object.preventExtensions()
  9. Object.getPrototypeOf()
  10. Object.setPrototypeOf()
  11. Object.defineProperty()
  12. Object.defineProperties()
  13. Object.getOwnPropertyDescriptor()
  14. Object.getOwnPropertyDescriptors()
  15. Object.getOwnPropertyNames()
  16. Object.is()
  17. Object.isFrozen()
  18. Object.isSealed()
  19. Object.isExtensible()
  20. Object.fromEntries()
  21. Object.hasOwnProperty()
  22. Object.hasOwn()
  23. Object.groupBy() (proposed feature, may not be fully available)

Object.create()
Object.create() is a method in JavaScript used to create a new object with a specified prototype object and optional properties. It allows for more fine-grained control over an object's prototype and properties compared to using object literals or constructors.

const personPrototype = {
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const john = Object.create(personPrototype);
john.name = "John";
john.greet();  // Output: Hello, my name is John
Enter fullscreen mode Exit fullscreen mode

Object.assign()
Object.assign() is a built-in JavaScript method used to copy the values of all enumerable own properties from one or more source objects to a target object. It performs a shallow copy and returns the modified target object.

const target = { a: 1 };
const source = { b: 2, c: 3 };
const result = Object.assign(target, source);
console.log(result);  // Output: { a: 1, b: 2, c: 3 }
console.log(target);  // Output: { a: 1, b: 2, c: 3 } (target is also modified)
Enter fullscreen mode Exit fullscreen mode

Object.keys()
Returns an array of the object’s own enumerable property names (keys)

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));  // Output: ['a', 'b', 'c']
Enter fullscreen mode Exit fullscreen mode

Object.values()
Returns an array of the object’s own enumerable property values

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));  // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Object.entries()
Returns an array of the object’s own enumerable property [key, value] pairs

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj));  // Output: [['a', 1], ['b', 2], ['c', 3]]
Enter fullscreen mode Exit fullscreen mode

Object.freeze()
Freezes the object, preventing new properties from being added or existing properties from being changed or deleted

const obj = { a: 1 };
Object.freeze(obj);
obj.a = 2;  // No effect, because the object is frozen
console.log(obj.a);  // Output: 1
Enter fullscreen mode Exit fullscreen mode

Object.seal()
Seals the object, preventing new properties from being added, but allows existing properties to be modified.

const obj = { a: 1 };
Object.seal(obj);
obj.a = 2;  // Allowed
delete obj.a;  // Not allowed
console.log(obj.a);  // Output: 2
Enter fullscreen mode Exit fullscreen mode

Object.preventExtensions()
Prevents any new properties from being added to the object, but allows modification and deletion of existing properties

const obj = { a: 1 };
Object.preventExtensions(obj);
obj.b = 2;  // Not allowed
console.log(obj.b);  // Output: undefined
Enter fullscreen mode Exit fullscreen mode

Object.getPrototypeOf()
Returns the prototype (i.e., the internal [[Prototype]]) of the specified object

const obj = {};
const proto = Object.getPrototypeOf(obj);
console.log(proto);  // Output: {} (the default Object prototype)
Enter fullscreen mode Exit fullscreen mode

Object.setPrototypeOf()
Sets the prototype of a specified object.

const proto = { greet() { console.log('Hello!'); } };
const obj = {};
Object.setPrototypeOf(obj, proto);
obj.greet();  // Output: 'Hello!'
Enter fullscreen mode Exit fullscreen mode

Object.defineProperty()
Defines a new property on an object or modifies an existing one, with additional options for property descriptors (e.g., writable, configurable).

const obj = {};
Object.defineProperty(obj, 'a', {
  value: 42,
  writable: false,  // Cannot modify the value
});
obj.a = 100;  // No effect because writable is false
console.log(obj.a);  // Output: 42
Enter fullscreen mode Exit fullscreen mode

Object.defineProperties()
Defines multiple properties on an object with property descriptors.

const obj = {};
Object.defineProperties(obj, {
  a: { value: 42, writable: false },
  b: { value: 100, writable: true }
});
console.log(obj.a);  // Output: 42
console.log(obj.b);  // Output: 100
Enter fullscreen mode Exit fullscreen mode

Object.getOwnPropertyDescriptor()
Returns the descriptor for a property of an object.

const obj = { a: 1 };
const descriptor = Object.getOwnPropertyDescriptor(obj, 'a');
console.log(descriptor);  
// Output: { value: 1, writable: true, enumerable: true, configurable: true }
Enter fullscreen mode Exit fullscreen mode

Object.getOwnPropertyDescriptors()
Returns an object containing all property descriptors for an object’s own properties

const obj = { a: 1 };
const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
// Output: { a: { value: 1, writable: true, enumerable: true, configurable: true } }
Enter fullscreen mode Exit fullscreen mode

Object.getOwnPropertyNames()
Returns an array of all properties (including non-enumerable ones) found directly on an object.

const obj = { a: 1 };
Object.defineProperty(obj, 'b', { value: 2, enumerable: false });
console.log(Object.getOwnPropertyNames(obj));  // Output: ['a', 'b']
Enter fullscreen mode Exit fullscreen mode

Object.is()
Compares if two values are the same (like === but handles special cases like NaN)

console.log(Object.is(NaN, NaN));  // Output: true
console.log(Object.is(+0, -0));    // Output: false
Enter fullscreen mode Exit fullscreen mode

Object.isFrozen()
Checks if an object is frozen

const obj = Object.freeze({ a: 1 });
console.log(Object.isFrozen(obj));  // Output: true
Enter fullscreen mode Exit fullscreen mode

Object.isSealed()
Checks if an object is sealed.

const obj = Object.seal({ a: 1 });
console.log(Object.isSealed(obj));  // Output: true
Enter fullscreen mode Exit fullscreen mode

Object.isExtensible()
Checks if new properties can be added to an object.

const obj = { a: 1 };
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj));  // Output: false
Enter fullscreen mode Exit fullscreen mode

Object.fromEntries()
Converts an array of key-value pairs into an object

const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj);  // Output: { a: 1, b: 2 }
Enter fullscreen mode Exit fullscreen mode

Object.hasOwnProperty()
Checks if an object has the specified property as its own (not inherited)

const obj = { a: 1 };
console.log(obj.hasOwnProperty('a'));  // Output: true
Enter fullscreen mode Exit fullscreen mode

Object.hasOwn()
Object.hasOwn() is a newer method introduced in ES2022 as an alternative to Object.hasOwnProperty(). It checks whether an object has a direct (own) property with a specified key, without looking up the prototype chain.

const obj = {
  name: 'Alice',
  age: 25
};

console.log(Object.hasOwn(obj, 'name'));  // true
console.log(Object.hasOwn(obj, 'gender'));  // false
Enter fullscreen mode Exit fullscreen mode

Object.groupBy
Object.groupBy is a relatively new feature proposed for JavaScript in ECMAScript 2024 that allows you to group objects based on a common criterion. It is not yet widely available across all environments, so it may not work in many browsers or JavaScript engines until fully implemented.

const array = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 },
];

// Group objects by age
const groupedByAge = Object.groupBy(array, item => item.age);

console.log(groupedByAge);

/*
Expected Output:
{
  25: [
    { name: 'Alice', age: 25 },
    { name: 'Charlie', age: 25 }
  ],
  30: [
    { name: 'Bob', age: 30 },
    { name: 'David', age: 30 }
  ]
}
*/

Enter fullscreen mode Exit fullscreen mode

Top comments (0)