LeeTee LeeTee - 2 months ago 17
jQuery Question

JQuery $.each() - struggling to get key value pairs of object

I have the following Object:

var business_challenges =[{title: 'Business Challenges'}, [{digital_trans: 'Digital Transformation'}, {agile_mobile:'Agile & Mobile Working always_on'}, {always_on:'Always on Infrastructure'}, {connect_protect: 'Connect & Protect'}, {cost_cutting:'Cost Cutting/Maximise Investment'}, {improving_cust: 'Improving Customer Engagement'} ]];
var business_divisions = [{title: 'Business Divisions'},[{SMB:'SMB'}, {DCS:'DCS'}, {DPS:'DPS'}]];
var filters = $.merge(business_divisions, business_challenges);


I am trying to loop through the object to get the key:value pairs but am struggling. The Key value is numeric instead of the associative array key and the value is an object. I have tried nesting another $each but this doesn't work.

Can anyone assist? Do I need to change how the filters object is put together?

var filter_html = '<ul>';
//var filtersJSON = $.parseJSON(filters);
$.each(filters, function(i, data) {
var filter_title = data.title; //THIS WORKS

filter_html = filter_html+filter_title;
$.each(data, function(key, val) {
filter_html = filter_html+'<li><input type="checkbox" value="'+ key +'">'+ val.key +'</li>'; //THIS DOESNT WORK

});

});
filter_html = filter_html+ '</ul>';


$('#filterControls').html(filter_html);

Answer

In order to

get the key:value pairs you may test each element in your each loop.

Indeed, the object filters contains objects and array of objects.

For array elements you can get the current object value with:

var key = Object.keys(val)[0];  // get the key name
var value = val[key];   // from the key name you can get the value

This because each object inside arrays has a different property name.

The snippet:

var business_challenges = [{title: 'Business Challenges'}, [{digital_trans: 'Digital Transformation'}, {agile_mobile: 'Agile & Mobile Working always_on'}, {always_on: 'Always on Infrastructure'}, {connect_protect: 'Connect & Protect'}, {cost_cutting: 'Cost Cutting/Maximise Investment'}, {improving_cust: 'Improving Customer Engagement'}]];
var business_divisions = [{title: 'Business Divisions'}, [{SMB: 'SMB'}, {DCS: 'DCS'}, {DPS: 'DPS'}]];
var filters = $.merge(business_divisions, business_challenges);
var filter_html = '<ul>';
$.each(filters, function (i, data) {
  if (Object.prototype.toString.call(data) === '[object Array]') {
    $.each(data, function (key, val) {
      var key = Object.keys(val)[0];
      var value = val[key];
      filter_html = filter_html + '<li><input type="checkbox" value="' + key + '">' + value + '</li>';
      console.log('Object N. ' + key + ': ' + JSON.stringify(val));
    });
  } else {
    filter_html = filter_html + data.title;
  }

});
filter_html = filter_html + '</ul>';


$('#filterControls').html(filter_html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="filterControls"></div>