1

I need to have similar JSON structure:

{
    "group1": ["A", "B", "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?

Radek Simko
  • 15,886
  • 17
  • 69
  • 107

1 Answers1

3

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/

treeface
  • 13,270
  • 4
  • 51
  • 57