jQuery iterate over object with $.each

点点圈 提交于 2019-12-02 01:41:08

问题


I have an object options: options = {title : 'title1', name : 'name1', url : 'url1', etc.}

which is passed in as a parameter to a function. I'm trying to iterate over that object, pass it through another function evaluate, and store the result in another object opts, like so:

var opts = new Object();

$.each(options, function(key,value){
opts.key = evaluate(element, value);
});

The evaluate(element,value) works fine, but the problem is that opts ends up looking like:

{key : eval(element,url1)}

instead of

{title : eval(element,title1), name : eval(element,name1), etc.}

That is, key gets passed literally instead of being evaluated, and gets overwritten with each iteration with the last property in options.

Do I have the right syntax in my assignment line? I also tried:

opts = {key : eval(element,val)}

which gave the same result as above. I can also convert the object to an array within the $.each iteration. I've tried several ways of doing that, also unsuccessfully. If someone can show me that route, that would be great too.

(This is for a jQuery plugin, and I'm testing using Firebug in Firefox).

Thanks in advance for your help.


回答1:


As you've discovered this is the literal key 'key':

opts.key = evaluate(element, value);

To use a dynamic key use []:

opts[key] = evaluate(element, value);

Specific example:

var o = {};
o["test"] = "foo";
alert(o.test);


来源:https://stackoverflow.com/questions/1897553/jquery-iterate-over-object-with-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!