Files
30-seconds-of-code/snippets/zip-object.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

24 lines
756 B
Markdown

---
title: Group array into object
tags: array,object
cover: baloons-field
firstSeen: 2017-12-21T00:55:18+02:00
lastUpdated: 2020-10-22T20:24:44+03:00
---
Associates properties to values, given array of valid property identifiers and an array of values.
- Use `Array.prototype.reduce()` to build an object from the two arrays.
- If the length of `props` is longer than `values`, remaining keys will be `undefined`.
- If the length of `values` is longer than `props`, remaining values will be ignored.
```js
const zipObject = (props, values) =>
props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});
```
```js
zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}
zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
```