Question

I have the following:

var new = {};
old.forEach(function (u) { new[u.id] = u.name; });

Can someone explain to me how I can implement this using the _.forEach that comes with lodash.

Was it helpful?

Solution

I thought lodash always produced an output and I would have to use that.

No, it really depends on the function. _.forEach just iterates over the elements of the collection. Even though it does return a value, it's just the collection you passed as first argument.

So I was thinking it would be more like: var new = _.foreach( .. Is there a way to do that or would I always need to do new[u.id} ?

You could use _.reduce, though I personally don't find it more readable than your version, because the intent is not as clear:

var newObj = _.reduce(old, function(obj, v) {
    obj[v.id] = v.name;
    return obj; // or in one line: return  obj[v.id] = v.name, obj;
}, {});

Ideally you would use something like _.map, which makes the intent much clearer, but you cannot map from an array to an object in general, and you cannot map from an object to an object with lodash (as it seems).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top