映射和过滤链接

时间:2017-02-26 21:58:41

标签: javascript functional-programming

数据看起来像这样

[{time: '09:00', 'level':'x3', 'type':'ae'}
time: '10:00', 'level':'x6', 'type':'fe'}
time: '09:00', 'level':'y3', 'type':'hy'}
time: '11:00', 'level':'z3', 'type':'hy'}]

我想得到的结果: 按时间过滤 - 09:00,并为相同类型创建分割数组。

示例结果:

{"levels": [ "x3","y3"],"types": ["ae","hy"]}

我可以在三个函数(过滤器和地图)中执行此操作,但我想将它们链接起来。是否有可能以更优雅的方式?

提前致谢。

3 个答案:

答案 0 :(得分:2)

注意:结果将是包含两个数组的对象。要获得该对象,您可以使用reduce,如下所示:



var arr = [
  {time: '09:00', 'level':'x3', 'type':'ae'},
  {time: '10:00', 'level':'x6', 'type':'fe'},
  {time: '09:00', 'level':'y3', 'type':'hy'},
  {time: '11:00', 'level':'z3', 'type':'hy'}
];

var result = arr.filter(o => o.time === '09:00')
                .reduce((acc, o) => {
                    acc.levels.push(o.level);
                    acc.types.push(o.type);
                    return acc;
                }, {levels: [], types: []});
   
console.log(result);




答案 1 :(得分:0)

只需过滤并映射所需的属性,然后获取具有所需属性和数组中所有值的对象。



var array = [{time: '09:00', 'level':'x3', 'type':'ae'}, {time: '10:00', 'level':'x6', 'type':'fe'},{time: '09:00', 'level':'y3', 'type':'hy'},{time: '11:00', 'level':'z3', 'type':'hy'}],
    result = array.
        filter(a => a.time === '09:00').
        map(({ level, type }) => ({ level, type })).
        reduce((r, o, i) => (Object.keys(o).forEach(k => (r[k] = r[k] || []).push(o[k])), r), {});
    
console.log(result);




答案 2 :(得分:0)

var tmp = [{time: '09:00', 'level':'x3', 'type':'ae'},
  {time: '10:00', 'level':'x6', 'type':'fe'},
  {time: '09:00', 'level':'y3', 'type':'hy'},
  {time: '11:00', 'level':'z3', 'type':'hy'}];

var result = {}; result.levels = []; result.types = [];

tmp.filter(data => data.time === '09:00').map(data => {
  result.levels.push(data.level);
  result.types.push(data.type);
});

console.log(result);