Monday, May 20, 2024
116
rated 0 times [  122] [ 6]  / answers: 1 / hits: 45652  / 13 Years ago, thu, november 24, 2011, 12:00:00

I have the following object



{ join: {} }


I'd like to find it's default object from the array below



[
{ login: { label: 'Login', url: '#login' } },
{ join: { label: 'Join', url: '#join', theme: 'a' } },
{ home: { label: 'none', icon: 'home', url: '#', theme: 'a' } }
]


I'd like to loop through the array and match the key, in this case 'join'.



This is what I have so far:



 var butt_to_find = { join: {} }
var all_buttons = 'array above'
var matching = _.find(all_buttons, function(default_button){
return if default_butt key @ 1 is the same as butt_to_find key @ 1;
});


This is the first time I've used underscore after hearing so much about it.
Any help, more than welcome


More From » underscore.js

 Answers
31
var buttons = [
{ login: { label: 'Login', url: '#login' } },
{ join: { label: 'Join', url: '#join', theme: 'a' } },
{ home: { label: 'none', icon: 'home', url: '#', theme: 'a' } }
]

_.find(buttons, function (button) { return 'join' in button })


The problem is that you're using a suboptimal data structure. This would make more sense, and produce simpler code:



var buttons = {
login: {label: 'Login', url: '#login'},
join: {label: 'Join', url: '#join', theme: 'a'},
home: {label: 'none', icon: 'home', url: '#', theme: 'a'}
}

buttons.join // equivalent to the `_.find` line in the first example (but much simpler)


Perhaps you're using an array because the order of the buttons is important. In this case, I'd use an array of arrays:



var buttons = [
['login', {label: 'Login', url: '#login'}],
['join', {label: 'Join', url: '#join', theme: 'a'}],
['home', {label: 'none', icon: 'home', url: '#', theme: 'a'}]
]

_.find(buttons, function (button) { return button[0] === 'join' })

[#88932] Tuesday, November 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cortez

Total Points: 326
Total Questions: 106
Total Answers: 110

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
;