Chi*_*hin 11 javascript underscore.js
我有以下对象
{ join: {} }
Run Code Online (Sandbox Code Playgroud)
我想从下面的数组中找到它的默认对象
[
{ login: { label: 'Login', url: '#login' } },
{ join: { label: 'Join', url: '#join', theme: 'a' } },
{ home: { label: 'none', icon: 'home', url: '#', theme: 'a' } }
]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我想遍历数组并匹配密钥'join'.
这是我到目前为止:
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;
});
Run Code Online (Sandbox Code Playgroud)
在听到这么多关于它之后,这是我第一次使用下划线.任何帮助,超过欢迎
dav*_*ers 20
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 })
Run Code Online (Sandbox Code Playgroud)
问题是你使用的是次优的数据结构.这会更有意义,并产生更简单的代码:
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)
Run Code Online (Sandbox Code Playgroud)
也许您正在使用数组,因为按钮的顺序很重要.在这种情况下,我将使用一组数组:
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' })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44069 次 |
| 最近记录: |