Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Last active July 4, 2018 12:59
Show Gist options
  • Save FlameWolf/fa7ba8d2c8ada0204de1bb1a2c98ec1a to your computer and use it in GitHub Desktop.
Save FlameWolf/fa7ba8d2c8ada0204de1bb1a2c98ec1a to your computer and use it in GitHub Desktop.

The power of Object.assign

Let's say you have an array like this:

let y = [{"a": { "id": 1 } }, { "b": { "id": 2 } }, { "c": { "id": 3 } }];

You can see that this is a very inefficient way to store data. It would be so much better to have these three distinct JSON objects as properties of a single JSON object like this:

{ "a": { "id": 1 }, "b": { "id": 2 }, "c": { "id": 3 } }

How can we achieve this?

Enter Object.assign:

y = Object.assign(...y, {});
// y == { "a": { "id": 1 }, "b": { "id": 2 }, "c": { "id": 3 } }

See that neat little thing I did with the spread (...) operator? That's where the magic happens. This kind of conversion of an array into a JSON object can come handy in another situation as well. Let me show you.

Let's say you have another JSON object like this:

let x = { "d": { "id": 4 }, "e": { "id": 5 } };

And you want to prepend the values of the array y to this object, because you'd like to have your keys in alphabetical order (or some other practical reason). You can use Object.assign for that:

x = Object.assign(...y, x);
// x == { "a": { "id": 1 }, "b": { "id": 2 }, "c": { "id": 3 }, "d": { "id": 4 }, "e": { "id": 5 } }

Isn't that neat? So this is how you can use Object.assign to:

  • Convert an array of JSON objects into a single JSON object
  • Prepend a JSON object with properties from another JSON object

Well, I hope this trick comes handy to you one day. Happy coding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment