Created
December 24, 2019 20:18
-
-
Save neharkarvishal/639d18855b47be03af8c3c9463f67a87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()
.