HomeToolsAbout

Object Methods

Object.entries

Returns an array of given object’s own enumerable string-keyed property key-value pairs in a tuple-like array

// object literal const obj = { foo: "bar", baz: 42 }; Object.entries(obj); // [['foo', 'bar'], ['baz', 42]] // Array-like object const obj = { 0: "a", 1: "b", 2: "c" }; console.log(Object.entries(obj)); // [['0', 'a'], ['1', 'b'], ['2', 'c']] // Array-like object with random key ordering const anObj = { 100: "a", 2: "b", 7: "c" }; Object.entries(anObj); // [['2', 'b'], ['7', 'c'], ['100', 'a']]

Object.keys

Returns an array of a given object’s own enumerable string-keyed property names. Works for array-like object.

// Simple array (returns index) const arr = ["a", "b", "c"]; Object.keys(arr); // ['0', '1', '2'] // Array-like object const obj = { 0: "a", 1: "b", 2: "c" }; Object.keys(obj); // ['0', '1', '2'] // Array-like object with random key ordering const anObj = { 100: "a", 2: "b", 7: "c" }; Object.keys(anObj); // ['2', '7', '100']

Usage on primitives

// Strings have indices as enumerable own properties Object.keys("foo"); // ['0', '1', '2'] // Other primitives have no own properties Object.keys(100); // []

Object.freeze()

What is it

Static method that freezes an object

  • Freezing an object prevents extensions and makes existing properties non-writable and non-configurable

A frozen object can no longer be changed:

  • new properties cannot be added
  • existing properties cannot be removed
  • their enumerability, configurability, writability, or value cannot be changed
  • the object's prototype cannot be re-assigned

freeze() returns the same object that was passed in

const obj = { prop: 42, }; Object.freeze(obj); // Throws an error in strict mode obj.prop = 33;

Object.freeze vs as const

Object.freeze is a runtime method whereas as const is compile time method

as const makes plain object not be able to be modified

const plainObject = { name: "josh", number: 1, status: "offline", } as const

Typing Object Destructuring

const obj = { a: 5, b: 7, c: 9 }; // Object.entries() Object.entries(obj).map(([key, value]) => { console.log(key); // a, b, c console.log(value); // 5, 7, 9 }) // for...of for(const [key, value] of Object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // using forEach Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" });
AboutContact