By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,175 Members | 1,710 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,175 IT Pros & Developers. It's quick & easy.

Chicken & Egg Problem Iterating Through Subset of JSON List

RMWChaos
100+
P: 137
In my ongoing effort to produce shorter, more efficient code, I have created a "chicken and egg" / "catch-22" problem. I can think of several ways to fix this, none of them elegant.

I want my code to declare var stop if it was not passed to the function. The problem is that stop would be equal to a value dependent on var index that has not been declared yet, but index cannot be created until stop is declared. So you see my chicken and egg problem.

At line 30 below, you can see that I declare stop when it is 'undefined'. However, index is not declared until line 42. So, how to handle this problem? And before you ask, no I haven't run this code yet because I know it won't work the way it is written. I'm not quite that dense. =D

Expand|Select|Wrap|Line Numbers
  1. // Example JSON list:
  2. jList = 
  3.     {
  4.     'memberOne'  :
  5.         {
  6.         'stringOne'  :  'valueOne',
  7.         'stringTwo'  :  'valueOne'
  8.         },
  9.     'memberTwo'   : 
  10.         {
  11.         'stringOne'  :  ['valueOne','valueTwo'],
  12.         'stringTwo'  :  ['valueOne','valueTwo']
  13.         };
  14.     };
  15.  
  16. /*
  17. * Split attribList and submit to createDOM()
  18. * attribList is original JSON list
  19. * member is 1st level member (by name or #) of attribList
  20. * start is begin object by node # (0, 1, 2...) only!
  21. * stop is end object by node # (0, 1, 2...) only!
  22. * if splitStart and splitStop are == only one node is created.
  23. */
  24.  
  25. function splitAttribList(attribList, member, start, stop)
  26.     {
  27.     // new list object //
  28.     var splitList = {};
  29.     // if start does not exist, create all values in member //
  30.     if (typeof stop == 'undefined')
  31.         {
  32.         var stop = attribList.member[index].length;
  33.         };
  34.     if (typeof start == 'undefined')
  35.         {
  36.         var start = 0;
  37.         };
  38.     // iterate from start to end of member //
  39.     for (var i = start; i <= stop; i++)
  40.         {
  41.         // create new list with selected member & values //
  42.         for (var index in attribList.member)
  43.             {
  44.             var value = attribList.member[index];
  45.             splitList[index] = value instanceof Array ? value[i] : value;
  46.             };
  47.         };
  48.     // submit new list to createDOM() //
  49.     createDOM(splitList);
  50.     };
  51.  
  52. // To test:
  53. function createDOM(attribList)
  54.     {
  55.     for (var index in attribList)
  56.         {
  57.         alert("Attrib/Value is: " + index + " / " + attribList[index]);
  58.         };
  59.     };
  60.  
If stop is not passed to the function, then it needs to be set to the end of the value list, but each value list may have a different length even within the same member. So I can't just set it to an arbitrary number, or I will get errors that the value does not exist.

One option is to declare "var index;" earlier, but I'm not sure if that would work when index is not set to any value. But that's about all I can think of at the moment. So is there another way to tell the code to stop iterating at the end of the value list without knowing how long the list may be? The only way I know is to use ".length".

By the way, would it be better to leave 'attribList' and 'member' as two separate values, or should I instead just use 'attribList' and pass 'jList.member' to the function?

Thanks!
Dec 11 '07 #1
Share this Question
Share on Google+
15 Replies


gits
Expert Mod 5K+
P: 5,320
heya ...

so have a look at the following code ... i made i working to test and simplified it as far as i could follow your explainations again :) ... at the moment the below code would produce:

Expand|Select|Wrap|Line Numbers
  1. {stringOne:1, stringTwo:1}
with the call in the last line.

Expand|Select|Wrap|Line Numbers
  1. var jList = {
  2.     'memberOne': {
  3.         'stringOne': 'valueOne',
  4.         'stringTwo': 'valueOne'
  5.     },
  6.     'memberTwo': {
  7.         'stringOne': ['valueOne','valueTwo'],
  8.         'stringTwo': ['valueOne','valueTwo']
  9.     } // no semicolon!
  10. };
  11.  
  12. function splitAttribList(attribList, member, start, stop) {
  13.     var splitList = {};
  14.  
  15.     if (typeof stop == 'undefined') {
  16.         // we have objects here and there is no length
  17.         // so we use a util-method :)
  18.         stop = obj_length(attribList[member]);
  19.     }
  20.  
  21.     if (typeof start == 'undefined') {
  22.         start = 0;
  23.     }
  24.  
  25.     // simplified ... at first :)
  26.     for (var index in attribList[member]) {
  27.         splitList[index] = 1
  28.     }
  29.  
  30.     createDOM(splitList);
  31. }
  32.  
  33. function obj_length(obj) {
  34.     var l = 0;
  35.  
  36.     for (var i in obj) {
  37.         l++;
  38.     }
  39.  
  40.     return l;
  41. }
  42.  
  43. function createDOM(attribList) {
  44.     for (var index in attribList) {
  45.         alert("Attrib/Value is: " + index + " / " + attribList[index]);
  46.     }
  47. }
  48.  
  49. splitAttribList(jList, 'memberTwo');
  50.  
now please show me with an example, what you expect/want to have as assigned values to the keys instead of the 1 that is now in. please forgive me, but i don't really have our last discussions in mind and i think that problem here is regarding it? so could you simply write one or two calls like i did above:

Expand|Select|Wrap|Line Numbers
  1. // pass any of your params here
  2. splitAttribList();
  3.  
and the object as splitList should turn out in that cases?

kind regards
Dec 12 '07 #2

Dasty
Expert 100+
P: 101
Just a side note: You have to make clear to yourself when you are working with "arrays" and when you are working with "object's properties". In JS, array is created just when you are working with integer indexes. Otherwise it's just object's properties (I really dont like when they are calling it associative "arrays" .. it just mess things up .. they are not arrays :) ). In your case, you are working with object's properties. The difference is, that object's properties dont have an order. (yes, it may look like they have in some browsers, where order of properties are chronological) But in general, using: "for (index in obj)" returns properties in RANDOM order. So there is no room for using "start" and "end", because we have no order and we have no integer indexes.

You maybe already knew that, I just wanted to point that out for other readers.

So "jList" objects are equivalent in both cases:

Expand|Select|Wrap|Line Numbers
  1. jList =
  2. {
  3.   'memberOne'  :
  4.   {
  5.     'stringOne'  :  'valueOne',
  6.     'stringTwo'  :  'valueOne'
  7.   },
  8.   'memberTwo'   :
  9.   {
  10.     'stringOne'  :  ['valueOne','valueTwo'],
  11.     'stringTwo'  :  ['valueOne','valueTwo']
  12.   }
  13. };
  14.  
Expand|Select|Wrap|Line Numbers
  1. jList =
  2. {
  3.   'memberTwo'   :
  4.   {
  5.     'stringTwo'  :  ['valueOne','valueTwo'],
  6.     'stringOne'  :  ['valueOne','valueTwo']
  7.   },
  8.   'memberOne'  :
  9.   {
  10.     'stringTwo'  :  'valueOne',
  11.     'stringOne'  :  'valueOne'
  12.   }
  13. };
  14.  
EDIT: fixed semicolons :) but the point stands ...
Dec 12 '07 #3

gits
Expert Mod 5K+
P: 5,320
hi ...

the semicolon within the object is not legal ... it will throw an error :) ... just to mention it again ...

kind regards
Dec 12 '07 #4

RMWChaos
100+
P: 137
Lol, alright you two. I got the semi-colon issue when I was testing; so thank you both, as always, for your replies. I probably could have worked this all out on my own, but it helps understand what the issues are when I have to type it all out and explain it. Besides, this is all much more interesting when I interact with the coding community.

gits: Yes, this is all related to our previous discussions; however, something major has changed. There are no longer multiple JSON lists with single levels each, but rather a single list with multiple levels. Make sense?

So here's where I was last night, but did not get to finish my post. I was too busy fixing the other stuff I messed up in my code when I was trying out different strategies. =D

1. I added 'var index;' at the beginning of the function.
2. I removed 'member' and will pass jList.member instead, which actually makes the code more flexible because it can accept any JSON structure, either single level or multiple levels deep.

Dasty: This code is working stricly with JSON (JavaScript Object Notation); so you are correct, they are not arrays. start and stop are purely integers passed to the function. For instance, look at the HTML code at the end of this example. start and stop define the beginning and end of i, which in turn describes the path to the values of the pairs listed in each member. Passing (jList.memberTwo, 0, 1) to the function would output string/value pairs jList.memberTwo.stringOne[0] through jList.memberTwo.stringTwo[1] in the following order:

Output:
stringOne : valueOne,
stringTwo : valueOne,
stringOne : valueTwo,
stringTwo : valueTwo

This is exactly what I want in the order I want, because all valueOnes are a list of attributes for a single DOM element, as are all valueTwos, etc. The problem I am facing now is that I get 'undefined' values when there is a mismatch in the number of values, which is not a problem, just annoying. For example if this were the JSON list:

Expand|Select|Wrap|Line Numbers
  1. jList =
  2.     {
  3.     'memberOne'  :
  4.         {
  5.         'stringOne'  :  'valueOne',
  6.         'stringTwo'  :  ['valueOne', 'valueTwo']
  7.         },
  8.     'memberTwo'   :
  9.         {
  10.         'stringOne'  :  ['valueOne','valueTwo', 'valueThree'],
  11.         'stringTwo'  :  ['valueOne','valueTwo']
  12.         }
  13.     };
  14.  
Then I would get an 'undefined' on memberOne.stringOne[1] and memberTwo.stringTwo[2]. So, now I am working on code that properly 'skips' 'undefined' values. Otherwise, I will have to use 'null' as a placeholder. Not the worst problem, as that is what I had to do with my older code. If all value lists are the same length, then all I need to do is tell my code to stop at memberXXX.stringOne.length, and that's easy enough to do.


Expand|Select|Wrap|Line Numbers
  1. function splitAttribList(attribList, start, stop)
  2.     {
  3.     var index;
  4.     var splitList = {};
  5.     // if start does not exist, create all values in member //
  6.     if (typeof start == 'undefined')
  7.         {
  8.         var start = 0;
  9.         };
  10.     if (typeof stop == 'undefined')
  11.         {
  12.         var stop = attribList[index].length;
  13.         };
  14.     // iterate from start to end of member //
  15.     for (var i = start; i <= stop; i++)
  16.         {
  17.         // create new list with selected values //
  18.         for (index in attribList)
  19.             {
  20.             var value = attribList[index];
  21.             splitList[index] = value instanceof Array ? value[i] : value;
  22.             };
  23.         };
  24.     // submit new list to createDOM() //
  25.     createDOM(splitList);
  26.     };
  27.  
  28. // and test code
  29. function createDOM(attribList)
  30.     {
  31.     for (var index in attribList)
  32.         {
  33.         alert("Attrib/Value is: " + index + " / " + attribList[index]);
  34.         };
  35.     };
  36.  
  37. // and html
  38. <button onclick="splitAttribList(jList.memberOne, 0, 0)">memberOne-0</button>
  39. <button onclick="splitAttribList(jList.memberTwo, 0, 0)">memberTwo-0</button>
  40. <button onclick="splitAttribList(jList.memberTwo, 1, 1)">memberTwo-1</button>
  41. <button onclick="splitAttribList(jList.memberTwo, 0, 1)">memberTwo-0,1</button>
  42.  
  43. // output:
  44. memberOne
  45. 1. stringOne : valueOne,
  46.    stringTwo : valueOne
  47.  
  48. memberTwo
  49. 2. stringOne : valueOne,
  50.    stringTwo : valueOne
  51. 3. stringOne : valueTwo,
  52.    stringTwo : valueTwo
  53. 4. stringOne : valueOne,
  54.    stringTwo : valueOne,
  55.    stringOne : valueTwo,
  56.    stringTwo : valueTwo
  57.  
Now let me consider further what the two of you have posted, particularly gits's insistence on using util-methods. I always push back initially on doing things that way, but generally give in to him in the end. But I do wish to point out that splitAttribList() is itself a util-method, removed from createDOM().

<sigh>
Dec 12 '07 #5

RMWChaos
100+
P: 137
In your case, you are working with object's properties. The difference is, that object's properties don't have an order (yes, it may look like they have in some browsers, where order of properties are chronological) But in general, using: "for (index in obj)" returns properties in RANDOM order. So there is no room for using "start" and "end", because we have no order and we have no integer indexes.
After re-reading your comments, you clarified something for me, but I have to disagree with you on one important point. For a better explanation than I can give, take a look at this site: JSON in Java.

Basically, it says that the JSONObjects between the { } braces are unordered (in my code these are the 1st level (memberOne, memberTwo) and the 2nd level (stringOne, stringTwo). Whereas the JSONArrays, between the [ ] brackets are ordered (in my code [valueOne, valueTwo]).

So start and stop do in fact work because i represents the values in the ordered JSONArray not the unordered Object properties in members or elements. For my purposes it doesn't matter which order the members or elements are in; they can be entirely unordered. The values have to be ordered though, and through use of the JSONArray, they are; so no problem.

Funny, gits had the same concern a few threads ago, but I explained what I was doing to him then as well. =D

Where you helped me is in understanding why "attribList[0]" didn't work. Because the members and elements are unordered, I have to reference them explicitly (attribList.memberOne.stringOne[0]). Or I can use var index to iterate through the elements in the members without referencing a specific element. On the other hand, this presents a problem with setting a default for stop when it is 'undefined'; each member has different element names.

I believe I have a workaround for this, but it is rather inelegant. Because the number of values are always the same within each member (memberOne elements will always have 2 values, memberTwo elements will always have 3, etc.) I can create a "reference element" under each member. The reference element will have the exact same number of null values as the rest of the elements have data values. Because the values are null, my code will not add them to splitList. But I can set my default code to "var stop = attribList.reference.length". I tested and this works perfectly!

Can you think of a better way to do this? Is there a way to make all levels JSONArrays? I tried various combinations of { } and [ ] but could not get it to work properly. At one point I was getting alerts that looked like this: "0 : object Object" rather than "stringXXX : valueXXX".

Here is the code that I have working:

Expand|Select|Wrap|Line Numbers
  1. // Example JSON list:
  2. var jList =
  3.     {
  4.     'memberOne'    :
  5.         {
  6.         'reference'   :  [null, null],
  7.         'stringOne1'  :  ['valueOne1', null],
  8.         'stringTwo1'  :  ['valueOne1', 'valueTwo1']
  9.         },
  10.     'memberTwo'    :
  11.         {
  12.         'reference'   :  [null, null, null],
  13.         'stringOne2'  :  ['valueOne2', 'valueTwo2', null],
  14.         'stringTwo2'  :  ['valueOne2', 'valueTwo2', 'valueThree2']
  15.         }
  16.     };
  17.  
  18. /*
  19. * Split attribList and submit to createDOM()
  20. * attribList is original JSON list
  21. * member is 1st level member (by name or #) of attribList
  22. * start is begin object by node # (0, 1, 2...) only!
  23. * stop is end object by node # (0, 1, 2...) only!
  24. * if splitStart and splitStop are == only one node is created.
  25. */
  26.  
  27. function splitAttribList(attribList, start, stop)
  28.     {
  29.     // if start does not exist, default to first value //
  30.     if (typeof start == 'undefined')
  31.         {
  32.         var start = 0;
  33.         };
  34.     // if stop does not exist, create all values in elements from start //
  35.     if (typeof stop == 'undefined')
  36.         {
  37.         var stop = attribList.reference.length;
  38.         };
  39.     // iterate from start to stop & create new list with selected values //
  40.     for (var i = start; i <= stop; i++)
  41.         {
  42.         var splitList = {};
  43.         for (index in attribList)
  44.             {
  45.             var value = attribList[index];
  46.             var newVal = value instanceof Array ? value[i] : value;
  47.             if (newVal != null)
  48.                 {
  49.                 splitList[index] = newVal;
  50.                 };
  51.             };
  52.         // submit new list to createDOM() //
  53.         createDOM(splitList);
  54.         };
  55.     };
  56.  
  57. // To test:
  58. function createDOM(attribList)
  59.     {
  60.     for (var index in attribList)
  61.         {
  62.         alert(index + " : " + attribList[index]);
  63.         };
  64.     };
  65.  
  66. // HTML (returns exactly what you'd expect)
  67. <button onclick="splitAttribList(jList.memberOne)">m1-v1-v2</button>
  68. <button onclick="splitAttribList(jList.memberTwo, 0, 0)">m2-v1</button>
  69. <button onclick="splitAttribList(jList.memberTwo, 1, 1)">m2-v2</button>
  70. <button onclick="splitAttribList(jList.memberTwo)">m2-v1-v2</button>
  71.  
Rock & Roll, it works! Pretty effective code for less than 30 lines, eh? <pats back> =D

Thanks again. Looking forward to your feedback.
Dec 12 '07 #6

Dasty
Expert 100+
P: 101
I misunderstood what was start and end for. Now I see it's index in arrays stored in object properties, not index of those properties. So order is fine ofc.
Dec 12 '07 #7

RMWChaos
100+
P: 137
I misunderstood what was start and end for. Now I see it's index in arrays stored in object properties, not index of those properties. So order is fine ofc.
Lol, almost exactly how gits responded. =D
Dec 13 '07 #8

gits
Expert Mod 5K+
P: 5,320
:) yep ... often we have an idea of what most people do wrong with some js-constructs ... so often when a 'newbie' uses something like objects, arrays, json, ajax etc. there are typical problems that you might have in mind and you don't look close enough on the real problem ... that teached me now when i have to read a post of yours, that isn't 'newbieish' :) ... to always have a closer look and think it over ... since you often have tricky things in your requirements :D

kind regards
Dec 13 '07 #9

RMWChaos
100+
P: 137
Well, am I a newb or not? LOL. No, I know that I'm still a newb even though I use more than just the basic JS and HTML code (which is generally the source of my problems). I haven't been coding long enough to be anything more than a newb. =D

As for my 'reference' element...I think it would be just as easy to set it to a number rather than enter in all the null values; so if all the elements in one member have 8 values, then I would set 'reference' : 8. The only problem is that my split code would not ignore this value and would create it in splitList. Perhaps I can just add if ((newVal != null) && (index != 'reference')). That should cover it.

Although this way would reduce the number of values in 'reference', I still have to include 'reference' in each member. Can you think of another way to get around this problem, or is this pretty much it for the way I've written the code?

Thanks!
Dec 13 '07 #10

gits
Expert Mod 5K+
P: 5,320
in case you ensure the list's length with filling in null-values you could leave the reference-element out and use a function to retrieve the list-length:

Expand|Select|Wrap|Line Numbers
  1. function get_list_length(attribList) {
  2.     for (var i in attribList) {
  3.         return attribList[i].length;
  4.     }
  5. }
in case you know how we could call such a function you will get the 'NO-newbie' title awarded :D

kind regards
Dec 13 '07 #11

RMWChaos
100+
P: 137
in case you ensure the list's length with filling in null-values you could leave the reference-element out and use a function to retrieve the list-length:

Expand|Select|Wrap|Line Numbers
  1. function get_list_length(attribList) {
  2.     for (var i in attribList) {
  3.         return attribList[i].length;
  4.     }
  5. }
in case you know how we could call such a function you will get the 'NO-newbie' title awarded :D

kind regards
LOL!
Well, here's my attempt. It works, from my test code.

Expand|Select|Wrap|Line Numbers
  1. // if stop does not exist, create all values in member from start //
  2. if (typeof stop == 'undefined')
  3.   {
  4.   for (var idx = 0 in attribList)
  5.     {
  6.     var stop = get_list_length(attribList);
  7.     };
  8.   };
  9.  
So do I get the "NO-newbie" title? =D
Dec 16 '07 #12

gits
Expert Mod 5K+
P: 5,320
*rofl* ... not enough yet :) ... you should have done a prayer to the term: 'util-method' ... :P ... but you get the title ... of course ... it is now officially awarded ... :)

kind regards
Dec 16 '07 #13

RMWChaos
100+
P: 137
What do you mean not enough yet? It worked, didn't it!? =D
Dec 16 '07 #14

gits
Expert Mod 5K+
P: 5,320
of course ... but i wanted you to say: 'i'll use a util method' ... anyway ... you got the title ... right? :D
Dec 17 '07 #15

RMWChaos
100+
P: 137
of course ... but i wanted you to say: 'i'll use a util method' ... anyway ... you got the title ... right? :D
Oh, you wanted me to say it. Well why didn't you say so? I'll use a util method. =D

Okay, I think this thread is officially closed.
Dec 17 '07 #16

Post your reply

Sign in to post your reply or Sign up for a free account.