Object.entries()

Object.entries() takes an object and then an array is returned containing the key-value pairs in the same order as the object.

Examples:

Outputting objects as arrays

const userObj = {
    firstName: 'Tom',
    lastName: 'Smith',
    age: 47
}

console.log(Object.entries(userObj)); //[ [ 'firstName', 'Tom' ], [ 'lastName', 'Smith' ], [ 'age', 47 ] ]

Looping through an object

Using the object from the previous example:

for (const [key, value] of Object.entries(userObj)){
    console.log(`${key}: ${value}`); //firstName: 'Tom'
}                                    //lastName: 'Smith'
                                     //age: 47

Coercing a non-object into an object

console.log(Object.entries('abc')); //[ [ '0', 'a' ], [ '1', 'b' ], [ '2', 'c' ] ]

An object with an unsorted key

const unSortedObj = {75: 'o', 15: 'n', 8: 'm'};
console.log(Object.entries(unSortedObj)); //[ [ '8', 'm' ], [ '15', 'n' ], [ '75', 'o' ] ]

Return an empty array

console.log(Object.entries(5)); //[]

An empty array can be returned for any type as long as it is a primitive data type. This excludes strings.

Convert an object to a map

const studentObj = {name: 'Greg', grade: 10, homeroom: '1A'};
const map = new Map(Object.entries(studentObj));
console.log(map); //Map { 'name' => 'Greg', 'grade' => 10, 'homeroom' => '1A' }

Object.fromEntries()

Object.fromEntries() does the opposite of Object.entries(), it takes key-value pairs and converts them to a single object.

Examples:

Converting an array into an object

const array = [[0, 'Tom'], [1, 'Bob'], [2, 'Sally'], [3, 'Sara']];

console.log(Object.fromEntries(array)); //{ '0': 'Tom', '1': 'Bob', '2': 'Sally', '3': 'Sara' }

Converting a map into an object

const map = new Map([['name', 'Greg'], ['grade', 10], ['homeroom', '1A']]);
const studentObj = Object.fromEntries(map);
console.log(studentObj); //{ name: 'Greg', grade: 10, homeroom: '1A' }