gpt4 book ai didi

javascript - Dstore过滤器: is there a way to compare properties?

转载 作者:太空宇宙 更新时间:2023-11-04 15:53:07 25 4
gpt4 key购买 nike

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

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/ ,但我对结果不太满意。有谁知道如何使用过滤器来完成该任务?

最佳答案

试试这个,它会返回安娜和朱莉的元素

        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

filter(query)

This filters the collection, returning a new subset collection. The query can be an object, or a filter object, with the properties defining the constraints on matching objects. Some stores, like server or RQL stores, may accept string-based queries. Stores with in-memory capabilities (like dstore/Memory) may accept a function for filtering as well, but using the filter builder will ensure the greatest cross-store compatibility.

编辑:具有更多属性进行比较的示例。您的函数只需要返回 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);
});

关于javascript - Dstore过滤器: is there a way to compare properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42955549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com