DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Temitope Ayodele
Temitope Ayodele

Posted on

Object.entries()

Object.entries() is used for listing all key-value pairs in an object. It accepts an object as a argument, and returns an array enumerating the key-value pairs of an object.

const obj = { 
  1: 'Israel', 
  2: 'Temi', 
  3: 'Miro' 
};
console.log(Object.entries(obj))

//Expected result: [ ["1", "Israel"], ["2", "Temi"], ["3", "Ayo"]]
Enter fullscreen mode Exit fullscreen mode

Another example:

const obj1 = {
  a: 'Hello',
  b: 28
};

for (let [key, value] of Object.entries(obj1)) {
  console.log(`${key}: ${value}`);
}

//Expected result: 
// "a: Hello"
// "b: 28"
Enter fullscreen mode Exit fullscreen mode

If the argument passed is not an object, it causes TypeError,
If the key passed in the argument is not in the range of the property[key, value] pair, it causes RangeError.

Top comments (2)

Collapse
 
pabloabc profile image
Pablo Berganza

Nice post for beginners ❀

Just a tip, if you want to have syntax highlighting in your post you can just add the language name directly after the first three backquotes of the code block!

It would look like this:

console.log('hi')
Collapse
 
temmietope profile image
Temitope Ayodele

Thanks!

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!