Skip to content

Instantly share code, notes, and snippets.

@bendc
Created July 8, 2016 09:24
Show Gist options
  • Save bendc/e1dc2087c2db3a7bfd72f19f54fc87ea to your computer and use it in GitHub Desktop.
Save bendc/e1dc2087c2db3a7bfd72f19f54fc87ea to your computer and use it in GitHub Desktop.
Friendlier object definition
const define = (object, ...pairs) =>
(Array.isArray(pairs[0]) ? pairs : [pairs]).reduce((accumulator, pair) => {
const [ key, value ] = pair;
return Object.defineProperty(accumulator, key, { value, enumerable: true });
}, object);
@bendc
Copy link
Author

bendc commented Jul 8, 2016

Example:

const obj = {};

// single property
define(obj, "foo", "bar");

// tuples
define(obj, ["a", 1], ["b", 2]);

console.log(obj); // => {foo: "bar", a: 1, b: 2}

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