473,756 Members | 8,174 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Chicken & Egg Problem Iterating Through Subset of JSON List

RMWChaos
137 New Member
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
15 2250
gits
5,390 Recognized Expert Moderator Expert
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
101 Recognized Expert New Member
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
5,390 Recognized Expert Moderator Expert
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
137 New Member
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.strin gOne[1] and memberTwo.strin gTwo[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.strin gOne.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
137 New Member
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.mem berOne.stringOn e[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.refe rence.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
101 Recognized Expert New Member
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
137 New Member
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
5,390 Recognized Expert Moderator Expert
:) 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
137 New Member
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

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

Similar topics

13
6353
by: rbronson1976 | last post by:
Hi all, I have a very simple page that Firefox has problems with: www.absolutejava.com/testing.htm First of all, this page seems to be perfectly valid XHTML Strict. Both the W3C validator as well as Page Valet indicate it is valid. The page is being served with the proper MIME type of "application/xhtml+xml". Unfortunately, Firefox will not display the page due to a non-breaking
3
2450
by: astarocean | last post by:
i'm using maildrophost to sendmail and wrote a script for it when the script is called directly from web request , a letter geneated with right things but when the script is called from json-rpc, the letter generated include a mess. see the file with this letter
0
5573
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
5
16133
by: Otto Wyss | last post by:
I've now been looking for a week for a simple but useful sample on how to get a list of entries (persons) via an XMLHttpRequest using Json/PHP on the server. So far I've found about a thousend different tutorials and code samples but not a single one, where the server returns an array of entries. Very few samples use Json at all and almost none show the server code. So does anybody know a sample which - uses just a small javascript...
21
1328
by: bearophileHUGS | last post by:
Once in while I too have something to ask. This is a little problem that comes from a Scheme Book (I have left this thread because this post contains too much Python code for a Scheme newsgroup): http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/a059f78eb4457d08/ The function multiremberandco is hard (for me still) if done in that little Scheme subset, but it's very easy with Python. It collects two lists from a given...
4
2545
by: UKuser | last post by:
Hi, I'm working on the following code, which works fine in Firefox, but not in IE. The problem is its not posting the variable to my page and I'm thinking its something wrong with the getElementByID but the code is as per an example on a tutorial website (http://www.tizag.com/ ajaxTutorial/ajax-javascript.php). The Select element is as follows: <select style="width:240px;font-size:8pt" id='servicet'
4
2822
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
19
1979
RMWChaos
by: RMWChaos | last post by:
Previously, I had used independent JSON lists in my code, where the lists were part of separate scripts. Because this method did not support reuse of a script without modification, I decided to consolidate all my JSON lists into one and modify my scripts so that they were more generic and reusable. So far so good. The problem is that my JSON lists used variables for many pieces of code that performed multiple iterations to create several...
4
8877
by: im12345 | last post by:
I have the following question: Im doing a sample application using dojo and json. I have 2 classes: 1. Book class package com.esolaria.dojoex; import org.json.JSONObject; import org.json.JSONException;
0
9212
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9779
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9645
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8645
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5247
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3742
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3276
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2612
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.