2016-10-06 30 views
0

的键值对,我有以下对象:

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

该数据结构是很奇怪的。你控制它的来源? – charlietfl

+0

是的,如果需要,我可以改变它。这是我第一次尝试在Javascript中放置一个关联数组/对象。我更习惯于PHP,所以我有点困惑! – LeeTee

+0

我认为你应该使用'$ .extend()'i.p.o. $ .merge()。 – Franco

回答

0

为了

拿到钥匙:值对 你可能在你的每个循环测试每个元素。

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

对于数组元素可以用得到当前对象值:

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

这是因为阵列内的每个对象具有不同的属性的名称。

的片段:

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>

+0

那正是我需要的,谢谢! – LeeTee