Iv read a lot of search results regarding how to deal with a JSON array that is returned from an Ajax function, but none seem to fit my problem.
Explain: I am effectively searching through a database in a tree like structure to return all of the child elements of a given element. There may be from 1 to many hundreds of results. All of this grunt work is done in PHP, which then returns a JSON array containing the results, however, I cant seem to work out how to iterate over the result, which looks like this:
{
"Kaz1Kid43343757245": {
"kaz1KidKid24572649":[],
"kaz1KidKid24572649Back":[]
},
"Kaz1Kid43343757245Back":[]
}
Note that each of the items needs to be returned as an individual ID, but if I try
$.each(obj, function(key, val)
{
//doing stuff with each item
});
I only get two of the results (Kaz1Kid43343757245 and Kaz1Kid43343757245Back) in the keys while the val's show nothing at all.
What am I doing wrong?
Cheers
MVK
This is an example of a recursive function, which will loop down into objects it encounters or add the key/value to a new, flat object:
function flatten(obj) {
var result = {};
function list(node) {
$.each(node, function(key, val){
if (jQuery.isPlainObject(val)) {
list(val);
} else {
result[key] = val;
}
});
}
list(obj);
return result;
}
http://jsfiddle.net/userdude/nssvk/
Or a tiny bit fancier way to run the first call:
http://jsfiddle.net/userdude/nssvk/1/
Which gives:
{
"Kaz1Kid43343757245Back" : []
"kaz1KidKid24572649" : []
"kaz1KidKid24572649Back" : []
}
Question is, what do you want to do with the "flattened away" keys such as Kaz1Kid43343757245
in your example object?
You need to recurse into the array. Your code only looks at the first level, but as you say yourself: it's a tree structure. So if an element is an array, you need to go in and get your values out again, And if those are arrays, you need to …
Let's rewrite the Object literal with proper indentation:
{
"Kaz1Kid43343757245": {
"kaz1KidKid24572649": [],
"kaz1KidKid24572649Back": []
},
"Kaz1Kid43343757245Back": []
}
I think it's obvious now why the loop iterates only over two properties. You will need to restructure the generated JSON.