Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Created December 24, 2019 20:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neharkarvishal/639d18855b47be03af8c3c9463f67a87 to your computer and use it in GitHub Desktop.
Save neharkarvishal/639d18855b47be03af8c3c9463f67a87 to your computer and use it in GitHub Desktop.
/**
* zipObject.js
* tags: { JavaScript, Array, Object }
* Given an array of valid property identifiers and an array of values,
* return an object associating the properties to the values.
* Since an object can have undefined values but not undefined property
* pointers, the array of properties is used to decide the structure of
* the resulting object using Array.prototype.reduce().
*/
const zipObject = (props, values) =>
props.reduce(
( obj, prop, index ) => (
( obj[prop] = values[index] ? values[index] : null ),
obj
), {}
);
console.log (
zipObject( ["a", "b", "c"], [1, 2] ) // {a: 1, b: 2, c: null}
);
console.log(
zipObject(["a", "b"], [1, 2, 3] ) // {a: 1, b: 2}
);
@neharkarvishal
Copy link
Author

zipObject.js

tags: { JavaScript, Array, Object }
Given an array of valid property identifiers and an array of values,
return an object associating the properties to the values.
Since an object can have undefined values but not undefined property
pointers, the array of properties is used to decide the structure of
the resulting object using Array.prototype.reduce().

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