jquery map 将虚线属性列表转换为对象
我想将这样的东西(例如在课堂上使用)转换
var classname = "username_admin color_red strength_good"
为
myvalues = {
username: 'admin',
color: 'red',
strength: 'good'
}
:这是目前我最接近的:
myvalues = $.map(classname.split(' '),function(el, i) {
var tmp = el.split('_');
var res = {};
res[tmp[0]] = tmp[1];
return res;
});
I would like to convert something like this (used in eg. in class):
var classname = "username_admin color_red strength_good"
into:
myvalues = {
username: 'admin',
color: 'red',
strength: 'good'
}
Here's at present my closest reach:
myvalues = $.map(classname.split(' '),function(el, i) {
var tmp = el.split('_');
var res = {};
res[tmp[0]] = tmp[1];
return res;
});
How to continue? http://jsfiddle.net/4EvWw/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会像这样使用each(),因为map()返回数组的元素,如文档中所述:
在这里小提琴 http://jsfiddle.net/4EvWw/1/
I'd use each() like this because map() returns element of an array as stated in the docs:
fiddle here http://jsfiddle.net/4EvWw/1/
您想要使用 .each 而不是 .map,并在函数之外定义 res:
http://jsfiddle .net/infernalbadger/4EvWw/3/
You want to use .each rather than .map, and define res outside of the function:
http://jsfiddle.net/infernalbadger/4EvWw/3/
将您的代码更新为以下 http://jsfiddle.net/manuel/4EvWw/2/
updated your code to the following http://jsfiddle.net/manuel/4EvWw/2/