【发布时间】:2014-08-28 14:26:28
【问题描述】:
我需要通过 json ID 在产品页面上设置三个类别元变量。每个产品页面可以在页面上包含任意数量的产品,并且每个产品都可以为这些类别中的每一个具有值。
如果产品 1 有值,我们就使用这些值。但是,如果产品 1 的值为 0(“无”类别)或未定义,则它需要进入下一个产品,依此类推,直到找到类别值,或者如果达到产品比较结束。
JSON
_jsonmeta = [
{ "Product": 1, "c1": 0, "c2": 1111, "c3": undefined },
{ "Product": 2, "c1": 2222, "c2": 2222, "c3": undefined }];
//should set category1=2222, category2 = 1111, category3 = 0 ('None')
然后我通过传入item和index来设置每个类别
function compareJson(json) {
$.each(json, function (i, item) {
//update if applicable
category1 = checkForNullOrZero(item.c1, i);
category2 = checkForNullOrZero(item.c2, i);
category3 = checkForNullOrZero(item.c3, i);
});
然后我需要一种方法来排序、过滤或将当前值与所有其他产品的相应类别进行比较。
function checkForNullOrZero(categoryidarg, indexarg) {
if (categoryidarg == null || typeof categoryidarg === 'undefined') {
//ignore it if undefined
console.log('Ignore: ' + categoryidarg);
}
else if (categoryidarg == 0) {
//check the others because this category is 'None'
console.log('Fall through to next: ' + _jsonmeta[indexarg]);
}
else {
//check the hierarchy to see if this Area trumps the others
console.log('Compare: ' + categoryidarg + ' vs ' + _jsonmeta[indexarg]);
}
//need to return category here
}
}
这是一个完整的小提琴:http://jsfiddle.net/TheFiddler/6mwpff7p/
【问题讨论】:
标签: javascript jquery json comparison