Object methods such as keys, values and entries are not difficult to understand. In this example we need to create an object with key-value pairs.
// //key: value const numbers = { one: 1, two: 2, three: 3 }; //
Object.keys()
This method will simply return all the keys of the given object. In this example the output should be an array containing one, two, three.
// console.log(Object.keys(numbers)); //one, two, three //
Object.values()
Same logic as keys method but instead of keys we get an array containing object’s values.
// console.log(Object.values(numbers); //1, 2, 3 //
Object.entries()
With this method the output will be slightly different and larger. Because this method will return both, the keys and the values as a single array for each key-value pair. To get each key and value after using the entries method we can use a for of loop and loop through the entries getting every single key and value as one pair.
// const entries = Object.entries(numbers); console.log(entries); // ["one", 1], ["two", 2], ["three", 3] for (const [key, value] of entries) { console.log(`${key}: ${value}`); //one: 1 two: 2 three: 3 } //