Reputation: 27399
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?
Upvotes: 1
Views: 474
Reputation: 1424
Short solution based on ES6 computed property names: { [obj.id]: obj }
Example:
var obj = {id: "2", name: "foo", price: "1"}
var transformed = { [obj.id]: obj }
console.log(transformed)
Upvotes: 4
Reputation: 10239
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?
Upvotes: 3