dojo 数据存储筛选器:是否有比较属性的方法?

sgtfey8w  于 2022-12-08  发布在  Dojo
关注(0)|答案(1)|浏览(148)

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

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/,但是我对结果不是很满意。有没有人知道用过滤器来完成那个任务的方法?

h79rfbju

h79rfbju1#

尝试此操作,它将返回项目安娜和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
筛选(查询)
这会筛选集合,并传回新的子集集合。查询可以是对象或筛选对象,其属性会定义相符对象的条件约束。有些存放区(例如服务器或RQL存放区)可能会接受字串型查询。具有内存中功能的存放区(例如dstore/Memory)也可能会接受筛选函式,但使用筛选产生器可确保最大的跨存放区相容性。

EDIT:要比较多个属性的示例。您的函数只需要返回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);
        });

相关问题