Created
March 15, 2016 17:32
-
-
Save piecyk/594f059babdbe2d42ba2 to your computer and use it in GitHub Desktop.
arrayToObject.js
This file contains hidden or 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
| function arrayToObject(a, key) { | |
| const getKey = (key, v, k) => { | |
| if (key === 'identity') { | |
| return v; | |
| } else if (key) { | |
| return v[key] || k; | |
| } else { | |
| return k; | |
| } | |
| } | |
| return _.reduce(a, (r, v, k) => ({...r, [getKey(key, v, k)]: v}), {}); | |
| } | |
| console.log(arrayToObject(['test', 'test1'])); | |
| //{"0":"test","1":"test1"} | |
| console.log(arrayToObject(['test', 'test1'], 'identity')); | |
| //{"test":"test","test1":"test1"} | |
| console.log(arrayToObject(['test', 'test1'], 'a')); | |
| //{"0":"test","1":"test1"} | |
| console.log(arrayToObject([{a:3, k:'test1'}, {a:2, k:'test2'}], 'k')); | |
| //{"test1":{"a":3,"k":"test1"},"test2":{"a":2,"k":"test2"}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment