Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 28th, 2012  |  syntax: None  |  size: 1.10 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. how to loop through an array with nested objects using jquery?
  2. var msg = [ {name: ["a1", "a2"], value: "this is A"},
  3.             {name: ["b1", "b2"], value: "this is B"},
  4.             ...
  5.           ]
  6.        
  7. var my_param = 'b1';
  8.  
  9. // This is an object, so we can have key/value pairs
  10. var error_codes =
  11. {
  12.     'a1': 0,
  13.     'a2': 0,
  14.     'b1': 1,
  15.     'b2': 1
  16. };
  17.  
  18. // This is an array because we only need values
  19. var error_messages =
  20. [
  21.     'This is A',
  22.     'This is b'
  23. ];
  24.  
  25. alert(error_messages[error_codes[my_param]]);
  26.        
  27. var error_codes = { 'a1': 1, }; // NO!
  28.        
  29. var value;
  30. $.each(msg, function (i, el) {
  31.   if (el.name.indexOf(name) >= 0) {
  32.     value = el.value;
  33.     return false;  // Stops iteration.
  34.   }
  35. });
  36.        
  37. var getMessage = function (name)
  38. {
  39.     var msg = [ ... ];
  40.  
  41.     for(var i = 0; i < msg.length; ++ i)
  42.         if (msg [i].name.indexOf (name) != -1)
  43.             return msg [i].value;
  44. }
  45.        
  46. var myMsg = findMsg('a1')
  47.  
  48.  
  49. function findMsg(msgType){
  50.   msg.forEach(function(obj){
  51.     if(inArray(msgType, obj.name) !== -1){
  52.       return obj.value
  53.     }
  54.   })
  55. }
  56.  
  57. function inArray(key, obj){
  58.  return obj.join().indexOf(key)
  59. }