Lee Li Lee Li - 2 months ago 7
Javascript Question

How to search the specific text in a nested object?

For example, I have a JSON array as follow, I will show it on a treelist ,so that user can select the item.Now there is a feature that allowing the user to search the specific text in the list. And the list is a nested list.I hava bind the JSON array to a treelist using HTML and Javascript. Now I should find a good way to search the specific text, and then return the object that include parent node when I find the text.

var allcategories=
[
{
"name": "shoes",
"subcategories": [
{
"name": "man's shoes",
"subcategories": [
{
"name": "sample name"
},
{
"name": "sample name",
"subcategories": []
}
]
},
{
"name": "woman's shoes",
"subcategories": []
}
]
},
{
"name": "cars",
"subcategories": [
{
"name": "cars1",
"subcategories": [
{
"name": "sample name"
},
{
"name": "sample name",
"subcategories": []
}
]
}
]
}
];


So now I want to use the
indexOf()
function to search the result. If the search is successful, the program should just return the parent category.Anyone have the same question in developing the codes?

Answer

As Bergi suggests, you can use a recursive function:

  function getCategory(categories, name) {
    var category, result;

    for (var i=0, iLen=categories.length; i<iLen; i++) {
      category = categories[i];

      if (category.name == name) {
        return category;

      } else if (category.subcategories) {
        result = getCategory(category.subcategories, name);

        if (result) return result;
      }
    }
    // return undefined if category name not found
  }

Note that this will return the first subcategory with a matching name, so the name needs to be unique.

Comments