views:

267

answers:

1

I have a json object that has properties into a type and product. I am looking for a way to loop through the elements and organize them into a tiered menu using YUI menu so the first level would group them by type and then the second menu would group them by product.

The json looks something like:

[{ "productId":1, "typeId": 1, "productName": "test", "typeName": "old", "itemId": 1, "itemName": "item1"},
{ "productId":2, "typeId": 2, "productName": "test2", "typeName": "new", "itemId": 2, "itemName": "item2"},
{ "productId":2, "typeId": 1, "productName": "test2", "typeName": "old", "itemId": 3, "itemName": "item3"}]

I would like to be able to loop through the items and add them to their correct submenu through looping, but the way that YUI menu is structured, doesn't seem to be an easy way to do this. The resulting menu structure would be something like:

  • old
    • test
      • item1
    • test2
      • item3
  • new
    • test2
      • item2

Question clarification: Looping through and creating individual items is easy enough:

for ( var i in obj )
{
    menu.addItem(obj[i].itemName);
}

What I need to do is to loop through creating submenus when they don't exists and appending the items to the submenus. All told there will be potentially up to like 200 items that will need to be sorted into these submenus so each branch will have several items. I'm looking for an easy way to do the check/create/append workflow.

A: 

Before attempting to create the list, sort the JSON data structure with a stable sort in the following order:

  1. Item Name (optional)
  2. Product Name
  3. Type Name

This will arrange the data in the same order as if you performed a depth-first search of the tree. Where

  • Old
    • Test 1
      • Item 3
      • Item 1
    • Test 2
      • Item 2
  • New
    • Test 2
      • Item 4

becomes

Old > Test 1 > Item 1
Old > Test 1 > Item 3
Old > Test 2 > Item 2
New > Test 2 > Item 4

Note that a change in the first or second column indicates that a new category or subcategory (respectively) must be created.

Unrelated to this question, you might want to consider a different method of displaying the data. From a user perspective, scrolling through a series of hierarchical drop-down menus that contains 200+ items is bound to be painful.

Mike Koval