473,721 Members | 2,259 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Partially iterating through JSON list looses attrib properties

RMWChaos
137 New Member
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 as you desire, iterating through all the elements in the list one after another. An additional feature allows you to select individual elements from the list rather than iterating through all of them at once. Okay, everything is good up to this point.

Now I've gone and asked my poor, overworked script to take on even more responsibility, and apparently it is just too much for the script to bear. I wanted to combine the individual element creation with the iteration functionality. Oh boy, let the fun begin!

If my JSON property lists were static, this whole issue would be moot. Unfortunately, the lists are dynamic (I like to make things difficult). For example, each element has a unique id that is determined by its function, location on the displayed HTML page, and other factors. Here is an example:

Expand|Select|Wrap|Line Numbers
  1. var page =
  2.     {
  3.     'homepage'   :  0,
  4.     'pagetwo'    :  1,
  5.     'pagethree'  :  2
  6.     };
  7.  
  8. for (var index in page)
  9.     {
  10.     var imageId = "nav" + index;
  11.     var navOptions =
  12.         {
  13.         'id'     :  imageId,
  14.         'dom'    :  'img',
  15.         'parent' :  'body'
  16.         };
  17.     createDOM(navOptions);
  18.     };
  19.  
Here you can see that imageId is dynamically created each time the for loop is run. That is fine as long as I am iterating through the entire list, but if I want to stop at a certain point (say at homepage) and later iterate through the rest (pageone and pagetwo), then everything breaks down because of the following code:

Expand|Select|Wrap|Line Numbers
  1. // Split attribList and submit to createNode //
  2. /*
  3. *  'attribList' (Str.) is the full JSON list passed to createDOM
  4. *  'split' (#) is the first element of the iteration section of the list
  5. *  'iterate' (#) is the current element to be created
  6. */
  7. function createDOM(attribList, split, iterate)
  8.     {
  9.     var splitList = {};
  10.     // if only split is listed, default iterate to 0 //
  11.     if (split && (typeof iterate == 'undefined'))
  12.         {
  13.         iterate = 0;
  14.         };
  15.     // if neither split nor iterate, create entire attribList (no split) //
  16.     if ((typeof split == 'undefined') || (split == 0))
  17.         {
  18.         createNode(attribList);
  19.         }
  20.     // if iterate is less that split or if split is null, create only value [iterate] per index //
  21.     else if ((split > iterate) || (split == null))
  22.         {
  23.         for (var index in attribList)
  24.             {
  25.             var value = attribList[index];
  26.             splitList[index] = value instanceof Array ? value[iterate] : value;
  27.             };
  28.         createNode(splitList);
  29.         }
  30.     // if iterate matches or exceeds split, create the remainder of values //
  31.     else if (split <= iterate)
  32.         {
  33.         for (var i = iterate; i < attribList.id.length; i++)
  34.             {
  35.             for (var index in attribList)
  36.                 {
  37.                 var value = attribList[index];
  38.                 splitList[index] = value instanceof Array ? value[i] : value;
  39.                 };
  40.             createNode(splitList);
  41.             };
  42.         };
  43.     };
  44.  
Originally, this was part of my createDOM() code, the very beginning in fact, but I am starting to think it needs to be attached to the script that is calling createDOM(). Was trying to remove redundancy since multiple scripts call this code, but because there is no easy way to pass all the vars and other JSON lists or Arrays that create the dynamic objects in the attribList...we ll, I may not have any alternative. I need to think about this some more. Maybe iteration recalls the original function to run again with a new variable ... originalFunctio n(i++)...hmm.
Dec 3 '07 #1
4 2818
RMWChaos
137 New Member
Oh wait, duh! <smacks forehead>

All I need to do is call the code currently called createDOM() inside my other scripts in order to create the new attribList, then pass attribList to the code that actually creates the DOM elements as many times as there are nodes to iterate through.

Sigh. Sometimes I just need to talk it out with you folks in order to understand my folly. =D

I'll report back here on the results.
Dec 3 '07 #2
gits
5,390 Recognized Expert Moderator Expert
hey ... :)

i'm looking forward to it ;)

kind regards
Dec 4 '07 #3
RMWChaos
137 New Member
hey ... :)

i'm looking forward to it ;)

kind regards
Don't hold your breath. =D

Still having problems, but I think I know what I need to do, I just need to figure out how to do it.

Instead of submitting the entire JSON list to createDOM() and splitting the list there, I need to split the list before I send it to createDOM(). The problem is that I need to include the code within the same function where all my vars are that create the JSON list in the first place, and then I still want to somehow make it modular rather than have to write the same code repeatedly within the scripts.

WAIT! Epiphany! A single, large JSON list, with deeper member levels of course, then just singly pick out the node to create. Iteration code is separate, but operates on the exact same principal of: for (i = #; i < #; i++)...hm, that could work, but talk about a major recode! Still, could be very efficient.

You know, I don't think I'll ever finish this darn website. I still have to code an XML (more probably JSON) -based forums system after the framework for the site is done. Never could get chatterbox to work.
Dec 4 '07 #4
RMWChaos
137 New Member
Ok, here's a start...much simplified:

Expand|Select|Wrap|Line Numbers
  1. // Split attribList and submit to createDOM //
  2. function splitAttribList(attribList, splitStart, splitStop)
  3.     {
  4.     for (var i = splitStart; i <= splitStop; i++)
  5.         {
  6.         var splitList = {};
  7.         for (var index in attribList)
  8.             {
  9.             var value = attribList[index];
  10.             splitList[index] = value instanceof Array ? value[i] : value;
  11.             };
  12.         createDOM(splitList);
  13.         };
  14.     };
  15.  
This will work for a single level JSON list. But what if it's multiple levels:

Expand|Select|Wrap|Line Numbers
  1. myJsonList = {
  2.     'navigation':  [
  3.         {
  4.         'id'    :  'idOne',
  5.         'dom'   :  'img',
  6.         'parent':  'body',
  7.         'src'   :  '../images/imageOne.jpg'
  8.         },{
  9.         'id'    :  'idTwo',
  10.         'dom'   :  'img',
  11.         'parent':  'body',
  12.         'src'   :  '../images/imageTwo.jpg'
  13.         },],
  14.     'loginForm' :  [
  15.         {
  16.         'id'    :  'login',
  17.         'dom'   :  'img',
  18.         'parent':  'body',
  19.         'src'   :  '../images/login.jpg'
  20.         },{
  21.         'id'    :  'logout',
  22.         'dom'   :  'img',
  23.         'parent':  'body',
  24.         'src'   :  '../images/logout.jpg'
  25.         },],
  26.     };
  27.  
  28. myJsonList.loginForm[1].id    // 'logout'
  29.  
So now the hard part: convert the code above to access this JSON structure...

Expand|Select|Wrap|Line Numbers
  1. /*
  2. * Split attribList and submit to createDOM
  3. * attribList is original JSON list
  4. * member is 1st level member (by name or #) of attribList
  5. * splitStart is begin object by node # (0, 1, 2...) only!
  6. * splitStop is end object by node # (0, 1, 2...) only!
  7. * if splitStart and splitStop are == only one node is created.
  8. */
  9. function splitAttribList(attribList, member, splitStart, splitStop)
  10.     {
  11.     // iterate from start to stop //
  12.     for (var i = splitStart; i <= splitStop; i++)
  13.         {
  14.         // new empty object //
  15.         var splitList = {};
  16.         // create all attribs in object member[i] //
  17.         for (var index in attribList[member][i])
  18.             {
  19.             var value = attribList[member][i];
  20.             // create new JSON list with single node and attribs //
  21.             splitList[index] = value instanceof Array ? value[index] : value;
  22.             };
  23.         // submit new list to createDOM() //
  24.         createDOM(splitList);
  25.         };
  26.     };
  27.  
  28. // to initiate
  29. splitAttribList(myJsonList, loginForm (or 1), 0, 0);  // this should create 'login' node //
  30.  
Is that right? If it is, that wasn't so hard after all. Just wrote it here, so I still have to test. I wonder if the structure of splitList will match the structure of the original JSON list, or if it will be a single-level list?? I think single...

Now if this works, how to convert the vars into strings in the original JSON list so that each attrib has a unique value? Sigh...more work.
Dec 4 '07 #5

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

Similar topics

20
6878
by: Luke Matuszewski | last post by:
Welcome As suggested i looked into JSON project and was amazed but... What about cyclical data structures - anybody was faced it in some project ? Is there any satisactional recomendation... PS i am ready to use JSON as data/object interchange when using AJAX and my J2EE project - because it is easier to traverse the JavaScript object than its XML representation (so of course may argue).
5
1655
by: Gerard Flanagan | last post by:
Hello all Could anyone shed any light on the following Exception? The code which caused it is below. Uncommenting the 'super' call in 'XmlNode' gives the same error. If I make XmlNode a subclass of 'object' rather than 'list' then the code will run. Thanks in advance. Exception:
3
10178
by: Adam | last post by:
I'm trying to retrieve some values from a json object, but instead it's giving me the property name. For example: var json = { "glossary": { "title": "example glossary" } }; console.log(json); alert(json.glossary.title); for (var x in json) { console.log(x); alert(x.title); } This will show me the json object in the console with glossary and title underneath it. When the alert for json.glossary.title fires, it
5
16130
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...
6
2176
by: dd | last post by:
I'm writing something in JS using the latest OO and JSON and I'm looking for a bit of guidance. I'm going to have this large object which has many top-level properties and some top-level functions. That part I have no problem with, I'll define it in JSON style (my prototype is working just fine). What I'll also have though, is some arrays at the top level. These arrays will contain n number of sub-objects. Each of these sub-objects will...
2
2516
by: holtmann | last post by:
Hi, I got a question regarding JSON as datasource- I understand that eval on a JSON String creates the appropriate objects in JS. But I would like to use JSON to supply data to already defined prototpye objects. I try to give an example. I e.g. got: address.prototype = { firstname: null;
23
3209
by: dhtmlkitchen | last post by:
JSON We all know what it is. In ECMAScript 4, there's a JSON proposal: Object.prototype.toJSONString String.prototype.parseJSON The current proposal, String.prototype.parseJSON, returns an object.
15
2247
RMWChaos
by: RMWChaos | last post by:
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...
19
1973
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...
0
9367
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9215
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9131
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
9064
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
8007
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
6669
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...
1
3189
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
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
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.