Copy all but some properties of an object in ES6

Since I started playing with ES6 about half a year ago I really came to love the new syntax, as it provides a much more python-ish feel to Javascript development.

One of the functions I like the most is the awesome Object.assign().

You can use it for all sorts of things:

const oldObject = { foo: 'bar', baz: 42 };
// (shallow) copy an object
const newObject = Object.assign({}, oldObject);
// overwrite some values
const overwritten = Object.assign({}, oldObject, { foo: 'fighters' });
// overwritten is { foo: 'fighters', baz: 42 }
// merge objects
const other = { luftballons: 99 };
const merged = Object.assign({}, oldObject, other);
// merged is { foo: 'bar', baz: 42, luftballons: 99 }

and more awesomeness that you can find, as always, on the MDN site.

One thing that I found out today that made my day better is that you can use Object.assign() to copy an object except for some of its properties.

const oldObject = { foo: 'bar', baz: 42 };
let noFoo = Object.assign({}, oldObject, { foo: undefined });
// noFoo is { foo: undefined, baz: 42 }
// this call is also equivalent to this
noFoo = { ...oldObject, foo: undefined };

[Edit – July 2019]: if you iterate through your items and check/filter for truthiness, this might be enough. However, if you can target ES2018, there’s a new syntax that actually removes the key as well:

const oldObject = { foo: 'bar', baz: 42 };
const { foo, ...noFoo } = oldObject
// now noFoo is { baz: 42 }

See this post about the rest/spread operator in ES2018

As easy as that!

I find myself doing this kind of operation quite often, namely when I decorate some object generated from JSON retrieved from a server and want to send it back after changing it client-side. This syntax makes it oh-so-simple!

6 thoughts on “Copy all but some properties of an object in ES6

  1. just use destructuration :

    “`
    const { foo, …rest } = oldObject;
    console.log(rest); // All but foo
    “`

    Like

  2. The topic should read ‘copy all but ONE’ instead of ‘copy all but SOME’… nice summary otherwise. If you can extend the body to match the topic it would be awesome

    Like

Leave a comment