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:
You're using
indexOf()
where you should be checking if an index isin
an objectYour
name
regex is checking for the prefix and yourprefix
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/
精彩评论