Skip to content

Instantly share code, notes, and snippets.

@piecyk
Created March 15, 2016 17:32
Show Gist options
  • Select an option

  • Save piecyk/594f059babdbe2d42ba2 to your computer and use it in GitHub Desktop.

Select an option

Save piecyk/594f059babdbe2d42ba2 to your computer and use it in GitHub Desktop.
arrayToObject.js
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