Browse Source

[object.fromArray]: fix extracting and building object

mightyplow 7 years ago
parent
commit
b1fd778666
2 changed files with 23 additions and 6 deletions
  1. 17 0
      src/object/__tests__/fromArray.test.js
  2. 6 6
      src/object/fromArray.js

+ 17 - 0
src/object/__tests__/fromArray.test.js

@@ -0,0 +1,17 @@
+import fromArray from '../fromArray';
+
+export default test => {
+    const ar = [{
+        foo: 'foo',
+        bar: 'bar'
+    }, {
+        foo: 'foo2',
+        bar: 'bar2'
+    }];
+
+    const extracted = fromArray(ar, 'foo', true);
+
+    test.ok(Object.keys(extracted).length === 2, 'length should be 2');
+    test.ok(Object.values(extracted).every(item => ar.includes(item)), 'all objects should be in result');
+    test.done();
+};

+ 6 - 6
src/object/fromArray.js

@@ -18,14 +18,14 @@ const fromArray = (array, key, keep = true) => {
         throw Error('key must be a string');
     }
 
-    return array.reduce((object, item) => {
-        const { prop, ...rest } = item;
+    return array.reduce((object, item = {}) => {
+        const { [key]: prop, ...rest } = item;
 
-        if (!prop) {
-            return object;
-        }
+        if (!prop) { return object; }
+
+        const value = item[key];
+        object[value] = keep ? item : rest;
 
-        object[prop] = keep ? item : rest;
         return object;
     }, {});
 };