Dstore过滤器:有没有办法比较属性?

时间:2017-03-22 15:07:31

标签: javascript dojo dstore

我们假设我有一个不同订单的商店。订单有送货地址和发票地址。地址本身有一个城市,街道等:

let data = [
        { id: 1, name: 'Anna', delivery: {city: "Amsterdam"}, invoice: {city: "Amsterdam"} },
        { id: 2, name: 'Anton', delivery: {city: "Amsterdam"}, invoice: {city: "Berlin"}}
];

我想过滤所有送货地址和发票地址都相同的订单。

我在jsFiddle中尝试过这个:https://jsfiddle.net/gbwv2bde/3/,但我对结果并不满意。有人知道使用Filter进行该任务的方法吗?

1 个答案:

答案 0 :(得分:1)

试试这个,它会返回项目Anna和Julie

        var data = [
            { id: 1, name: 'Anna', delivery: { city: "Amsterdam" }, invoice: { city: "Amsterdam" } },
            { id: 2, name: 'Anton', delivery: { city: "Amsterdam" }, invoice: { city: "Berlin" } },
            { id: 3, name: 'John', delivery: { city: "Berlin" }, invoice: { city: "Paris" } },
            { id: 4, name: 'Julie', delivery: { city: "Paris" }, invoice: { city: "Paris" } }
        ];

        var myStore = new Memory({ data: data, idProperty: 'id' });
        var myResultsSet = myStore.filter(function (object) {
            return object.delivery.city === object.invoice.city;
        });

        myResultsSet.forEach(function (item) {
            console.log("item ", item.name);
        });

基本上你可以创建一个自己的函数传递给filter(),你可以用它来编写自己的比较逻辑。

请点击此处了解更多详情 https://github.com/SitePen/dstore/blob/master/docs/Collection.md

  

过滤器(查询)

     

这会过滤集合,返回新的子集集合。该   query可以是具有属性的对象或过滤器对象   定义匹配对象的约束。有些商店,比如服务器   或者RQL存储,可以接受基于字符串的查询。内存中的商店   功能(如dstore / Memory)可以接受过滤功能   同样,但使用过滤器构建器将确保最大   跨店兼容性。

编辑:包含更多要比较的属性的示例。您的函数只需返回true或false(如果对象与您的比较条件匹配,则为true)

        var data = [
            { id: 1, name: 'Anna', delivery: { city: "Amsterdam", price: 5 }, invoice: { city: "Amsterdam", price: 20 } },
            { id: 2, name: 'Anton', delivery: { city: "Amsterdam", price: 8 }, invoice: { city: "Berlin", price: 7 } },
            { id: 3, name: 'John', delivery: { city: "Berlin", price: 10 }, invoice: { city: "Paris", price: 20 } },
            { id: 4, name: 'Julie', delivery: { city: "Paris", price: 2 }, invoice: { city: "Paris", price: 3  } }
        ];

        //example for custom filtering with nested properties
        var myStore = new Memory({ data: data, idProperty: 'id' });
        var myResultsSet = myStore.filter(function (object) {
            if(object.delivery.city === object.invoice.city){
                if (object.delivery.price < 5 && object.invoice.price < 5)
                    return true;
            }else
                return false;
        });

        myResultsSet.forEach(function (item) {
            console.log("item ", item.name);
        });