DEV Community

Michal M.
Michal M.

Posted on • Originally published at geodev.me

Spread the object and omit keys

Lastly I needed to create a shallow copy of an object but omit some keys. To make the code more compact I didn't want to use the delete operator. ES6 spread operator allows to do it.

Below is an example original object. I want to copy it but omit the city and country keys.

const user = {
    age: 20,
    name: 'Garry',
    city: 'Copenhagen',
    country: 'Denmark'
};

const { city, country, ...userCopy } = user;

console.log(userCopy);

/**
{
    "age": 20,
    "name": "Garry"
}
**/
Enter fullscreen mode Exit fullscreen mode

However, this solution creates new, unused variables (city and country) with their values:

console.log(city) // 'Copenhagen'
console.log(country) // 'Denmark'
Enter fullscreen mode Exit fullscreen mode

Ideally we don't want to create any side effects. Here's the solution.

function omitKeys(keys, obj) {
    const excluded = new Set(keys);
    return Object.fromEntries(Object.entries(obj).filter(e => !excluded.has(e[0])))
}

console.log(omitKeys(['city, country'], user));
/**
{
    "age": 20,
    "name": "Garry"
}
**/

console.log(city) // city is not defined;
console.log(country) // country is not defined;
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs