4

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.

9
  • 3
    Lambda? items.forEach(item => addData(item.data)); Commented Dec 22, 2016 at 19:44
  • I don't think there's any shorthand in regular Javascript. Libraries like underscore.js and lodash probably have ways to do it. Commented Dec 22, 2016 at 19:44
  • iirc cant you bind the function argument to a function @Barmar? Commented Dec 22, 2016 at 19:45
  • @SterlingArcher How would that automatically get the .data property of every element of the array? Commented Dec 22, 2016 at 19:45
  • You could adjust the addData function to look for .data :P Commented Dec 22, 2016 at 19:46

3 Answers 3

1

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() { }.

Sign up to request clarification or add additional context in comments.

3 Comments

How about a little items.forEach(({ data }) => addData(data));
Is that fancy destructuring I see?
Thats right. Whats the point of programming if you don't get to make yourself feel clever? haha
0

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

1 Comment

While this is true, Barmar had a good point that this doesn't generalize the solution. OP might not want to do that and is looking for a way to bind the item.data param, not item
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.