根据地图和动态用户选择生成排除列表

时间:2018-01-15 05:31:46

标签: javascript arrays object ecmascript-6 lodash

我有一个查找对象,其中的键是tourIds,值是该游览的可用目的地。

用户应该能够选择个别城市。但是,我需要根据用户选择的城市禁用不可用作游览目的地的城市。

举个例子我们可以看到3个城市的名单:罗马,佛罗伦萨和威尼斯,还有参观佛罗伦萨和威尼斯的旅游。因此,如果用户选择佛罗伦萨和威尼斯,则必须禁用罗马。

这是我的查询

{
    "1": ["Paris"],
    "2": ["London"],
    "3": ["Rome"],
    "4": ["Florence"],
    "5": ["Venice"],
    "12": ["Paris", "London"],
    "13": ["Paris", "Rome"],
    "14": ["Paris", "Florence"],
    "15": ["Paris", "Venice"],
    "21": ["London", "Paris"],
    "23": ["London", "Rome"],
    "24": ["London", "Florence"],
    "25": ["London", "Venice"],
    "123": ["Paris", "London", "Rome"],
    "124": ["Paris", "London", "Florence"],
    "125": ["Paris", "London", "Venice"],
    "213": ["London", "Paris", "Rome"],
    "214": ["London", "Paris", "Florence"],
    "215": ["London", "Paris", "Venice"],
    "1234": ["Paris", "London", "Rome", "Florence"],
    "1235": ["Paris", "London", "Rome", "Venice"],
    "2134": ["London", "Paris", "Rome", "Florence"],
    "2135": ["London", "Paris", "Rome", "Venice"],
    "21345": ["London", "Paris", "Florence", "Venice"]
}

并假设用户选择了这两个城市:

selecteddCities = ["Venice", "Florence"]

我需要一个数组,disabledCities,其中包括根据当前选定的城市没有游览该目的地的城市。在这种情况下,罗马。因为没有游览威尼斯,佛罗伦萨和罗马。

可以使用ES6和Lodash。什么是最好的wat来生成disabledCities数组?

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解,但我猜你想要将主列表过滤到2个已启用列表的游览和禁用游览。并且要启用游览,它需要包含所有用户选择的城市。下面是一些示例代码,用于根据用户选择的数组过滤掉这些代码。



var tours = [
    {tourIds : "1", cities : ["Paris"]},
    {tourIds : "2", cities : ["London"]},
    {tourIds : "3", cities : ["Rome"]},
    {tourIds : "4", cities : ["Florence"]},
    {tourIds : "5", cities : ["Venice"]},
    {tourIds : "12", cities : ["Paris", "London"]},
    {tourIds : "13", cities : ["Paris", "Rome"]},
    {tourIds : "14", cities : ["Paris", "Florence"]},
    {tourIds : "15", cities : ["Paris", "Venice"]},
    {tourIds : "21", cities : ["London", "Paris"]},
    {tourIds : "23", cities : ["London", "Rome"]}
]

var userSelCities = ['Paris','London']



var areCitiesInTour = function(tour){

    var CitiesFound = 0

        for (var i = 0; i < tour.cities.length; i++) {

            for (var x = 0; x < userSelCities.length; x++) {
                if (tour.cities[i] === userSelCities[x]) {
                    CitiesFound += 1;
                }
            }
        }


    return(CitiesFound === userSelCities.length);
}

var areCitiesNotInTour = function(tour){

    var CitiesFound = 0

    for (var i = 0; i < tour.cities.length; i++) {

        for (var x = 0; x < userSelCities.length; x++) {
            if (tour.cities[i] === userSelCities[x]) {
                CitiesFound += 1;
            }
        }
    }


    return(CitiesFound !== userSelCities.length);
}

    var enableTours =  tours.filter(areCitiesInTour)
    var disabledTours = tours.filter(areCitiesNotInTour)

    console.log(enableTours)
    console.log(disabledTours)
&#13;
&#13;
&#13;