1

I'm trying to get multiple attributes from unordered lists from multiple divs that look like this:

    <div class="graph" style="display:none;">
        <ul g-max='10'>
            <li g-color='green' g-val='4'></li>
            <li g-color='blue' g-val='3.6'></li>
            <li g-color='red' g-val='8'></li>
        </ul>
    </div>

    <div class="graph" style="display:none;">
        <ul g-max='14'>
            <li g-color='green' g-val='2'></li>
            <li g-color='blue' g-val='9'></li>
            <li g-color='red' g-val='3.98'></li>
        </ul>
    </div>

I'm trying to do this with jQuery and I'm using the following:

    var graph_array = [];

    $('.graph').each(function(divind)
    {
          $('ul').each(function(ulind)
          {
               $('li').each(function(liind)
               {
                     graph_array[divind][ulind][liind]['g-val'] = $(this).attr('g-val');
                     graph_array[divind][ulind][liind]['g-color'] = $(this).attr('g-color');
               });
          });
    });
    alert(graph_array);

But, even when I move things around and try different techniques like .map() or .toArray(), nothing works. Any ideas? Thanks in advance!

EDIT: I'm wanting to have an ending result that'll look like this:

    [{
       {
         {g-color:green, g-val:4},{g-color:blue, g-val:3.6},{g-color:red, g-val:8}
       },
       {
         {g-color:green, g-val:2},{g-color:blue, g-val:9},{g-color:red, g-val:3.98}
       }
    }]
7
  • Can you show the array/object you want to end up with? Commented Oct 20, 2012 at 20:27
  • 3
    I'm not exactly sure what you hope to have at the end, but I will say this: when you say $('li').each, it's going to loop through every li on the page -- not just the ones that are inside the ul that the parent loop is referencing. Perhaps you want something like $(li, ulind).each, which would constrain the selector to the given context. (And you would need to do this at each level, of course.) Commented Oct 20, 2012 at 20:27
  • it would help if you add desired output.. Commented Oct 20, 2012 at 20:30
  • 1
    Woah, not legal! What about [ {green:4, blue:3.6, red:8}, {green:2, blue:9, red:3.98} ];, or similar. This is legal js, and contains all the data available. Commented Oct 20, 2012 at 20:51
  • 1
    Cool! You've got at least one good answer below anyway. Commented Oct 20, 2012 at 20:57

3 Answers 3

2

You need to instantiate the arrays or pre-populate them. Like this, for example:

var graph_array = [];
$('.graph').each(function(divind, e)
{
      $(e).find('ul').each(function(ulind, e)
      {
           $(e).find('li').each(function(liind, e)
           {
               // create level 1 sub-array, or use existing
               var level1 = (graph_array[divind] || (graph_array[divind] = []));

               // create or re-use level #2 sub-array
               var level2 = (level1[ulind] || (level1[ulind] = []));

               // create a property map
               var map = (level2[liind] = {});
               map ['g-val'] = $(e).attr('g-val');
               map ['g-color'] = $(e).attr('g-color');
           });
      });
});
// display as a string
alert(JSON.stringify(graph_array));​

See here for a working example: http://jsfiddle.net/Q57W5/5/

Sign up to request clarification or add additional context in comments.

7 Comments

Nice! This works well. But, I noticed that you said that I should assume two arrays. Is there I a way to make it to take any amount of different divs? I'm wanting to make it a little more versatile so that it'll recognize all divs with the .graph class.
@Cod-nerd I realized that would be better, after I posted -- see my edited answer.
I've tried this on your jsfiddle link and it works great, but it fails on my own page. I looked through the jquery and I'm not recognizing stringify. Is this relative jsfiddle or a specific package?
@Cod-nerd JSON.stringify it standard as of Javascript 1.7: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
@Cod-nerd here's the browser support for it ... IE7 and below does not support it. caniuse.com/json
|
1

The main thing to look out for here is that you did not initialize the arrays you were trying to append to. You'll need to initialize an array for each group. Another thing to do here is utilize the scope of the each function and one of its two parameters.

$.each($(element_array),function(index,elem){
  // $(this)
  // $(elem) 
});

I've listed two interchangeable ways you can use the scope of the each and also utilize the this keyword. When you are in each iteration of the each loop, the current item can be found in the $(this) variable. You could also use $(elem).

In cases where you have nested each commands, I find it better to use a different variable for each nested loop and not use this. I find it less confusing.

So basically what you need to do is use the relative current variable to search within its decedents.

var graph_array = [];

$('.graph').each(function(divIndex,currentDiv) {
  if (graph_array[divIndex] == undefined){ graph_array[divIndex] = []; }
  $(currentDiv).find('ul').each(function(ulIndex,currentUl) {
    if (graph_array[divIndex][ulIndex] == undefined){ graph_array[divIndex][ulIndex] = []; }
    $(currentUl).find('li').each(function(liIndex,currentLi) {
      if (graph_array[divIndex][ulIndex][liIndex] == undefined){ graph_array[divIndex][ulIndex][liIndex] = []; }     
      graph_array[divIndex][ulIndex][liIndex]['g-val'] = $(currentLi).attr('g-val');
      graph_array[divIndex][ulIndex][liIndex]['g-color'] = $(currentLi).attr('g-color');
    });
  });
});

console.log(graph_array);​

Live Demo

Comments

0

Do something like this:-

var graphArray = new Array();
$(".graph ul li").each(function(i) {
    graphArray[i] = $(this).attr("g-color") + ":" + $(this).attr("g-val");
});

alert(graphArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.