1

I've the following unordered list:

<ul class="primary">
    <li id="1"><span>Product Family A</span>
       <ul class="secondary">
           <li><span>A.1</span></li>
           <li><span>A.2</span></li>
       </ul>
    </li>
    <li id="2"><span>Product Family B</span>
       <ul class="secondary">
           <li><span>B.1</span></li>
       </ul>
    </li>
    etc...
</ul> 

I'd like to generate the output below with jQuery. Can someone help?

product_family:[{
   id:1,
   products:[{
      model: A1,
      model: A2
}],
product_family:[{
   id:2,
   products:[{
      model: B1
}]

THanks!

2
  • api.jquery.com/jquery.each and api.jquery.com/children and api.jquery.com/text Commented May 16, 2012 at 16:37
  • Your proposed output is nonsensical. JS/JSON field names are unique within a particular object; with duplicate keys of product_family and model within the same object, the second instance will just blow away the first. You're trying to treat JSON like XML and you can't. Commented May 16, 2012 at 16:39

2 Answers 2

1
var out = [];
$('ul.primary > li').each(function(index, val) {
    out[index] = {
        product_family : this.id,
        products: []
    };
    $('ul > li', this).each(function() {
        out[index].products.push({
            model: $('span', this).text()
        });
    })
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks much, this is close. It's missing the 'id' as one of the key in the product_family. Right now it's printing out as such: [{"product_family":"1","products":[{"model":"A.1"},{"model":"A.2"}]}].
0

Please note that this part is invalid:

products:[{
    model: A1,
    model: A2
}],

I'll assume you meant to write this:

products:[
    { model: A1 },
    { model: A2 }
}],

You can use something like this:

var pf = [];
$("ul.primary").children("li").each(function(i,e) {
    var products = [];
    $(e).find('ul').find('span').each(function(i2,e2) {
        products.push({ model: $(e2).find('ul') });
    });
    pf.push( {
        id: (i+1),
        products: products
    });
});

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.