Toran Billups Toran Billups - 1 month ago 5
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 item.id; });


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

You can do this directly with a function:

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

Is that what you are looking for?