Objects methods (assign, keys, values, entries and fromEntries)

In this article, you will learn some very useful methods for manipulating objects in JavaScript. Some of them would enable you to combine with array methods such as Array.map and Array.filter to produce the result that you want.

Let's discuss using examples from JSONPlaceholder, a popular free fake API for testing.

Data

The data that we are going to use are from this async function:

async function fetchText() { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const originalObj = await response.json(); console.log('originalObj', originalObj) } fetchText()

The result is an object:

// originalObj { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }


Object.assign()

There are many ways to copy an object, Object.assign is one of them. It meant to assign properties from one object to another. The easiest example to understand it is to call this method with an empty object (i.e. target) and another object (i.e. source) makes a copy of the second object.

Thereby, we can create a shallow clone of an object.

async function fetchText() { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const originalObj = await response.json(); const targetObj = Object.assign({}, originalObj); console.log('targetObj', targetObj); console.log('originalObj', originalObj) console.log('originalObj === targetObj', originalObj === targetObj) } fetchText()

As you can see, the targetObj looks exactly like the originalObj but they are not, as confirmed from the result of strict equality.

The result is:

// targetObj { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } // originalObj { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } // originalObj === targetObj false


Object.keys()

Before Object.keys, if we want to loop through each of an object's properties we can use for-in loop.

const obj = { userId: 1, id: 1, title: "delectus aut autem", completed: false }; for (const key in obj) { console.log(`${key}: ${obj[key]}`); }

The result is:

userId: 1 id: 1 title: delectus aut autem completed: false

With Object.keys, we are returned an array that contains the keys of the object, which allow us to chain with array methods.

const obj = { userId: 1, id: 1, title: "delectus aut autem", completed: false }; const keys = Object.keys(obj) console.log(keys) const values = Object.keys(obj).map(item => obj[item]) console.log(values)

The result is:

// keys ['userId', 'id', 'title', 'completed'] // values [1, 1, 'delectus aut autem', false]

Other useful application of Object.keys is to check the length of an object

const objLength = Object.keys(targetObj).length

There are numerous situation that you may need this checking. For example, in the below object, if none of the ‘address’ fields is filled which make the property: ‘address’(i.e. object) empty and as a result, zero in array length if using the above checking. Then we could display some placeholders instead of blank field.

The result is:

const obj = { userId: 1, id: 1, title: "delectus aut autem", completed: false, address: { // blank field } }; console.log(Object.keys(obj.address).length)

The result is:

0


Object.values()

Object.values is similar to Object.keys, which the latter returns us the keys of an object and the former returns us the values of an object

const obj = { userId: 1, id: 1, title: "delectus aut autem", completed: false }; const keys = Object.keys(obj); const values = Object.values(obj); console.log(keys); console.log(values);

The result is:

// keys ['userId', 'id', 'title', 'completed'] // values [1, 1, 'delectus aut autem', false]


Object.entries() and Object.fromEntries()

Object.entries and Object.fromEntries are often seen appeared together because they allows you to converts an object into array and do the reverse respectively. This allows us to use all the Array and Object built-in methods.

Object.entries()

It convert the key/value paris of an object into a nested array with each internal array consists of the key at index 0 and the value at index 1

const obj = { userId: 1, id: 1, title: "delectus aut autem", completed: false }; const nestedArray = Object.entries(obj); console.log(nestedArray);

The result is

// nestedArray [ ['userId',1], ['id',1], ['title', 'delectus aut autem'], ['completed', false] ]


Object.fromEntries()

Object.entries allows us to utilize a bunch o array methods, but what if want to convert it back into object? Object.fromEntries would do the trick.

const array = [ ['userId',1], ['id',1], ['title', 'delectus aut autem'], ['completed', false] ]; const resultObj = Object.fromEntries(array); console.log(resultObj);

The result is

{ userId: 1, id: 1, title: "delectus aut autem", completed: false };