我有以下对象:
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值是数字而不是关联数组的键,并且该值是一个对象。我已经尝试嵌套另一个$each,但这不起作用。
有人能帮忙吗?我是否需要更改过滤器对象的组合方式?
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);
为了
获取键:值对您可以测试每个循环中的每个元素。
实际上,对象过滤器包含对象和对象数组。
对于数组元素,您可以使用以下命令获取当前对象的值:
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>
try $.each(myObject, function(keyName, keyValue)
var myObject = {
string: 'someText',
number: 123321,
array: [1, 2, 3, 4]
};
$.each(myObject, function(keyName, keyValue) {
console.log(keyName + ': ' + keyValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>