Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to pick only some fields from an object

Short answer

Destructuring takes the needed fields, and you put them into a new object:

const user = { id: 1, name: 'Anna', email: 'anna@example.com', password: 'secret' };
const { name, email } = user;
 
console.log(JSON.stringify({ name, email }));

Output:

{"name":"Anna","email":"anna@example.com"}

A list of keys

When the keys are in an array, build the object with Object.fromEntries():

const pick = (object, keys) => Object.fromEntries(keys.filter((key) => key in object).map((key) => [key, object[key]]));
 
const user = { id: 1, name: 'Anna', email: 'anna@example.com', password: 'secret' };
 
console.log(JSON.stringify(pick(user, ['id', 'name', 'phone'])));

Output:

{"id":1,"name":"Anna"}

By values

Filter the pairs of the object to drop, for example, empty values:

const form = { name: 'Anna', phone: '', city: 'Rome', note: null };
const filled = Object.fromEntries(Object.entries(form).filter(([, value]) => value !== '' && value !== null));
 
console.log(JSON.stringify(filled));

Output:

{"name":"Anna","city":"Rome"}

Common mistake

Without the key in object check, missing keys become properties with undefined:

const user = { name: 'Anna' };
const picked = Object.fromEntries(['name', 'phone'].map((key) => [key, user[key]]));
 
console.log(Object.keys(picked).join(', '));

Output:

name, phone

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.