【问题标题】:Compare Json in Hierachy to Set Vars将层次结构中的 Json 与 Set Vars 进行比较
【发布时间】: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


    【解决方案1】:

    为此,您必须从checkForNullOrZero 函数返回 (1) 当前类别的值或 (2) 该类别的当前产品的值。

    我认为将类别定义为数组可能更容易:

    var categories = [undefined,undefined,undefined];
    

    然后将compareJson函数改成这样:

    function compareJson(json) {
        $.each(json, function (i, item) {
            //update if applicable
            categories[0] = checkForNullOrZero(item.c1, 0);
    
            categories[1] = checkForNullOrZero(item.c2, 1);
    
            categories[2] = checkForNullOrZero(item.c3, 2);
        });
    }
    

    然后通过checkForNullOrZero 函数,您可以访问categories[indexarg],如果新值没有覆盖它,您应该返回原始值。

    这里有一个工作小提琴:

    http://jsfiddle.net/6mwpff7p/5/

    此解决方案的一个问题是检查每个产品,即使所有类别都已设置。更好的解决方案可能是使用 for 循环。摆弄这个方法是:http://jsfiddle.net/6mwpff7p/6/

    【讨论】:

    • 很好,第二种方法更好。我会去的,谢谢。
    猜你喜欢
    • 2017-06-10
    • 2019-06-14
    • 2022-07-21
    • 1970-01-01
    • 2022-01-08
    • 2021-08-29
    • 1970-01-01
    • 2015-02-15
    • 2013-02-07
    相关资源
    最近更新 更多