2
\$\begingroup\$

I use jQuery and underscore.js, I have title1-2 and I would like to have the action corresponding.

this.items = {
    menuItems: [
        { title: 'title1',
            data: [
                { title: 'title1-1',
                    action: 'action1-1'
                },
                { title: 'title1-2',
                    action: 'action1-2'
                }
                ]
        },
        { title: 'title2',
            data: [
                { title: 'title2-1',
                    action: 'action2-1'
                },
                { title: 'title2-2',
                    action: 'action2-2'
                }
            ]
        }
    ]
};

Currently, I have the following code to do this:

var item = _.find(_.flatten(_.pluck(this.items.menuItems, 'data')), function (item) { return item.title === 'title1-2'; });
console.log(item.action);

Is there a better way to find it?

\$\endgroup\$
2
  • \$\begingroup\$ So I assume that you want to find the object that contains title1-2? \$\endgroup\$ Commented May 23, 2012 at 11:22
  • \$\begingroup\$ exactly, thx :) \$\endgroup\$
    – freuh
    Commented May 23, 2012 at 12:37

1 Answer 1

1
\$\begingroup\$

Actually the only improvement I think you can make is that you use the chaining sugar, looks a lot better:

var item = _.chain(items.menuItems)
  .pluck('data')
  .flatten()
  .find(function(a){
    return a.title === 'title1-2'
  })
  .value()
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.