Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Generating JSON objects dynamically in JavaScript

Posted: September 26, 2015
Written by: Saints At Play
Category: Javascript

Working with JSON provides front-end developers with many advantages over other data formats, least of which is the fact that it's a subset of the JavaScript language itself.

In this short tutorial we'll take you through dynamically generating a JSON object within JavaScript...

Let's say, for the sake of illustration, that we want to loop through a list of HTML elements and retrieve product data from which we will then use to create a JSON object for posting via AJAX.

Our HTML might look something like this:

 <ul class="products-list">
    <li data-code="102462" 
        data-quantity="1" 
        data-price="35">Sample product heading #1</li>
    <li data-code="792365" 
        data-quantity="2" 
        data-price="18">Sample product heading #2</li>
    <li data-code="258193" 
        data-quantity="5" 
        data-price="24">Sample product heading #3</li>
 </ul> 

With a little help from jQuery here's how we could create our JSON object:

var products           =   {"productData”:[]};

$('li').each(function(index)
{
  var productCode      =   $(this).data('code'),
      productQuantity  =   $(this).data('quantity'),
      productPrice     =   $(this).data('price');

  products.productData.push({
    "code": productCode, 
    "quantity":parseInt(productQuantity), 
    "price":parseInt(productPrice)
  });
});

We could, if we felt so inclined, re-write our loop sequence like so, to help optimise the script a little further:

var products           =   {"productData”:[]};

$('li').each(function(index)
{
  products.productData.push({
    "code": $(this).data('code'), 
    "quantity":parseInt($(this).data('quantity')), 
    "price":parseInt($(this).data('price'))
  });
});

In both of the above examples we begin by defining our JSON object, followed by iterating through all of the list items where we retrieve the values from the appropriate data attributes which are then pushed into our JSON object as key/value pairs.

Nice and easy huh? Told you it would be a short tutorial!

« Return to Posts

Comments

There are no comments

Posting comments after three months has been disabled.