JQuery $ .each() - 努力获取对象的键值对

时间:2016-10-06 21:00:31

标签: jquery loops object each associative-array

我有以下对象:

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); 

我试图遍历对象以获取密钥:值对但是我正在努力。 Key值是数字而不是关联数组键,值是对象。我已经尝试过嵌套另外的$,但这不起作用。

有人可以帮忙吗?我是否需要更改过滤器对象的放置方式?

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);

1 个答案:

答案 0 :(得分:2)

为了

  

获取密钥:值对   你可以测试每个循环中的每个元素。

实际上,对象过滤器包含对象和对象数组。

对于数组元素,您可以使用以下命令获取当前对象值:

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

这是因为数组中的每个对象都有不同的属性名称。

摘录:

&#13;
&#13;
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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="filterControls"></div>
&#13;
&#13;
&#13;