Reputation: 1926
The following obviously doesn't work but it is the goal I am trying to reach:
items.forEach(addData(item.data));
I know I can do:
items.forEach(function(item){
addData(item.data)
});
but I was wondering if there was a shorthand / cooler way of doing this.
edit:
I am also calling the same add data function with an array of items that aren't nested like so:
items.forEach(addItemId)
Which is why I was trying to find a way to use the same function (in a similar) fashion for the nested object.
Upvotes: 4
Views: 2091
Reputation: 169
I don't necessarily recommend doing this in production code, but you can accomplish something like this with a little combinator:
const map_into = k => fn => o => fn(o[k]);
items.forEach(map_into('data')(addData));
Upvotes: 0
Reputation: 22405
Use an ES6 feature: Lambdas.
items.forEach(item => addData(item.data));
I'm trying to find a way to use .bind
here, but to be honest, this is a pretty clean way. One liner, shorthand for function() { }
.
Upvotes: 1
Reputation: 28750
If you can update your function to use item
instead of item.data
you could do this:
items.forEach(addData);
This will call addData with each item
, not item.data
though
Upvotes: 0