Toran Billups Toran Billups - 3 years ago 153
Javascript Question

How to map an object by given key using lodash?

I have an object that looks something like this

{id: "2", name: "foo", price: "1"}

I want to transform this to the following

{2: {id: "2", name: "foo", price: "1"}}

I'm able to achieve this today if I wrap this object with a simple array like so thanks to the friendly keyBy method for array

_.keyBy([action.response], function(item) { return; });

What I would prefer of course is the same result but without having to wrap this with an array first. Does transform/reduce or some other lodash v4 method provide this functionality?

Answer Source

You can do this directly with a function:

function convert(obj) {
 var result = {}
 result[] = obj
 return result

Is that what you are looking for?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download