Merge pull request #1111 from 30-seconds/update-object-to-pairs

Update object to pairs
This commit is contained in:
Angelos Chalaris
2020-03-23 15:11:03 +02:00
committed by GitHub
4 changed files with 59 additions and 3 deletions

View File

@ -5,12 +5,12 @@ tags: object,array,beginner
Creates an array of key-value pair arrays from an object.
Use `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.
Use `Object.entries()` to get an array of key-value pair arrays from the given object.
```js
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
const objectToPairs = obj => Object.entries(obj);
```
```js
objectToPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]
```
```

23
snippets/toPairs.md Normal file
View File

@ -0,0 +1,23 @@
---
title: toPairs
tags: object,array,intermediate
---
Creates an array of key-value pair arrays from an object or other iterable (object, array, string, set etc.).
Check if `Symbol.iterator` is defined and, if so, use `Array.prototype.entries()` to get an iterator for the given iterable, `Array.from()` to convert the result to an array of key-value pair arrays.
If `Symbol.iterator` is not defined for `obj`, use `Object.entries()` instead.
```js
const toPairs = obj =>
obj[Symbol.iterator] instanceof Function && obj.entries instanceof Function
? Array.from(obj.entries())
: Object.entries(obj);
```
```js
toPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]
toPairs([2, 4, 8]); // [ [0, 2], [1, 4], [2, 8] ]
toPairs('shy'); // [ ['0', 's'], ['1', 'h'], ['2', 'y'] ]
toPairs(new Set(['a', 'b', 'c', 'a'])); // [ ['a', 'a'], ['b', 'b'], ['c', 'c'] ]
```

View File

@ -0,0 +1,16 @@
---
title: objectToEntries
tags: object,array,beginner
---
Creates an array of key-value pair arrays from an object.
Use `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.
```js
const objectToEntries = obj => Object.keys(obj).map(k => [k, obj[k]]);
```
```js
objectToEntries({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]
```

17
test/toPairs.test.js Normal file
View File

@ -0,0 +1,17 @@
const {toPairs} = require('./_30s.js');
test('toPairs is a Function', () => {
expect(toPairs).toBeInstanceOf(Function);
});
test('Creates an array of key-value pair arrays from an object.', () => {
expect(toPairs({ a: 1, b: 2 })).toEqual([['a', 1], ['b', 2]]);
});
test('Creates an array of key-value pair arrays from an array.', () => {
expect(toPairs([2, 4, 8])).toEqual([[0, 2], [1, 4], [2, 8]]);
});
test('Creates an array of key-value pair arrays from a string.', () => {
expect(toPairs('shy')).toEqual([['0', 's'], ['1', 'h'], ['2', 'y']]);
});
test('Creates an array of key-value pair arrays from a set.', () => {
expect(toPairs(new Set(['a', 'b', 'c', 'a']))).toEqual([['a', 'a'], ['b', 'b'], ['c', 'c']]);
});