AddyProg
AddyProg

Reputation: 3050

Search through JSON to find sepcific values

I am trying to search a JSON from client to get specific value , linear search is working if i go with specific keys but when i search from a key in middle of json it returns nothing. Here is what i am trying

$.each(jsonStr, function (i, v) {

    var folderID = '1408614499420';
    if (v['@id'] == folderID) {
        alert(v.folder.file['@id']);
    }

});

I want to search a specific folder by its id and get all files in that specific folder. Here is the Fiddle with actual json.

Upvotes: 1

Views: 91

Answers (1)

vikrant singh
vikrant singh

Reputation: 2111

do u want something like this

$("#menuArea li").live('click', function (event) {
$.each(jsonStr.hierarchy.folder["folder"], function (i, v) {
    var folderID ='1408614499420';//any id of folder
   if (v['@id'] == folderID) {
        alert(v.file['@id']);//file where folder id is folderID 
    }

});
      event.stopPropagation();
    });

Here's working fiddle http://jsfiddle.net/9kw99L2h/6/

Edit :-

Code for getting all subfolders & files

function getAllSubFolders(folder) {
    var subFolders = [];
    if (folder.folder) {
        if (folder.folder instanceof Array) {
            for (var i = 0; i < folder.folder.length; i++) {
                subFolders[subFolders.length] = folder.folder[i]['@id'];
               subFolders = subFolders.concat(getAllSubFolders(folder.folder[i]))
            }
        } else {
            subFolders[subFolders.length] = folder.folder['@id'];
            subFolders = subFolders.concat(getAllSubFolders(folder.folder))
        }
    }
    return subFolders;
}

function getAllFiles(folder) {
    var files = [];
    if (folder.file) {
        if (folder.file instanceof Array) {
            for (var i = 0; i < folder.file.length; i++) {
                files[files.length] = folder.file[i]['@id'];
            }
        } else {
            files[files.length] = folder.file['@id'];
        }
    }
    if (folder.folder) {
       files = files.concat(getAllFiles(folder.folder));
    }
     return files;
}

Fiddle http://jsfiddle.net/9kw99L2h/9/

Upvotes: 1

Related Questions