Javascript集合使用Lodash

时间:2017-05-24 11:00:35

标签: javascript lodash

我有一个如下所示的数组。我想知道出发和到达领域内的哪些值。

数组:

var data = {
    "origin": "Antalya",
    "destination": "IST",

    "flights": [{
        "provider": "thy",
        "time": "2017-07-07 10:30",
        "legs": [{
            "departure": "AYT",
            "arrival": "IST"
        }]
    },{
        "provider": "thy",
        "time": "2017-07-07 14:30",
        "legs": [{
            "departure": "AYT",
            "arrival": "ESB"
        },{
           "departure": "ESB",
            "arrival": "IST" 
        }]
    },{
        "provider": "pegasus",
        "time": "2017-07-07 06:30",
        "legs": [{
            "departure": "AYT",
            "arrival": "ADB"
        },{
            "departure": "ADB",
            "arrival": "IST"
        }]
    }]
};

我想要像这样的新数组:

[ “AYT”, “IST”, “ESB”, “亚”]

我如何使用lodash处理它?<​​/ p>

2 个答案:

答案 0 :(得分:2)

循环遍历数据并创建字符串数组,然后使用uniq函数,如:

var data = {"origin":"Antalya","destination":"IST","flights":[{"provider":"thy","time":"2017-07-07 10:30","legs":[{"departure":"AYT","arrival":"IST"}]},{"provider":"thy","time":"2017-07-07 14:30","legs":[{"departure":"AYT","arrival":"ESB"},{"departure":"ESB","arrival":"IST"}]},{"provider":"pegasus","time":"2017-07-07 06:30","legs":[{"departure":"AYT","arrival":"ADB"},{"departure":"ADB","arrival":"IST"}]}]};

var legs = [];
_.each(data.flights, flight => {
  _.each(flight.legs, leg => {
    legs.push(leg.departure);
    legs.push(leg.arrival);
  });
});

console.log(_.uniq(legs));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

答案 1 :(得分:2)

这是使用lodash的解决方案:

let result = _(data.flights)
    .flatMap('legs')
    .flatMap(_.values)
    .uniq()
    .value();

首先,我们得到一个扁平的腿数组,在最终获得唯一值之前,将其转换为每条腿属性值的扁平数组。