开发者

How to fill in the JSON in cycle?

I need to have similar JSON structure:

{
    "group1": ["A", "B",开发者_如何学Go "C"],
    "group2": ["C", "D", "E"],
    "group3": ["F", "G", "H"]
}

and need to create it in cycle:

courses.each(function(index) {
    name = $(this).attr("href").replace(/([^\/]*)\/.*/, "$1");
    prefix = $(this).attr("href").replace(/[^\/]*\/(.*)/, "$1");

    if (subjects.indexOf(prefix) == -1) {
        subjects[prefix] = new Array();
    }

    subjects[prefix].push(name);
});

The courses variable is DOM object from sth like this:

<a href="group1/A">...
<a href="group1/B">...
<a href="group2/D">...

After the cycle execution, it contents sth like this:

[Array[0], "group1", "group2"]

not the structure mentioned above...

Why?


Your problem stems from two things:

  1. You're using indexOf() where you should be checking if an index is in an object

  2. Your name regex is checking for the prefix and your prefix regex is testing for your name

So in order to solve this, you need to use this code:

courses.each(function(index) {
    var prefix = $(this).attr("href").replace(/([^\/]*)\/.*/, "$1"),
        name = $(this).attr("href").replace(/[^\/]*\/(.*)/, "$1");

    if (!(prefix in subjects)) { //here test using the "in" operator
        subjects[prefix] = []; //shorthand array notation
    }

    subjects[prefix].push(name);
});

You can see a working example here:

http://jsfiddle.net/ErUvC/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜