如何通过属性过滤一组嵌套数据?

时间:2017-07-11 19:32:40

标签: javascript arrays functional-programming

问题: 如何根据最后生效日期过滤/摘取每个组中的对象?

code sample On repl.it

const isLatestDate = (prev, test) => {
  return test.effectiveDate > prev.effectiveDate;
};

 var groupedByName = { 
   abc: 
     [ { name: 'abc', effectiveDate: '2016-01-01T00:00:00+00:00' },
       { name: 'abc', effectiveDate: '2016-04-01T00:00:00+00:00' },
       { name: 'abc', effectiveDate: '2016-05-01T00:00:00+00:00' } ],
   abcd: 
     [ { name: 'abcd', effectiveDate: '2016-02-01T00:00:00+00:00' },
       { name: 'abcd', effectiveDate: '2016-09-01T00:00:00+00:00' } ]
  }
// let output = groupedByKeyNames.reduce((acc, item) =>{
//     acc[item]=[acc[item].sort((a,b)=>(new Date(a.effectiveDate))-(new Date(b.effectiveDate))).pop()];
// },{})  
let groupedByKeyNames = Object.keys(groupedByName);

let output = groupedByKeyNames.reduce((acc, item) => {
  // does key exsist
  // yes - skip
  // no - add it.
  if(!acc[item]){
    acc[item] = {};
  }
  acc[item] = groupedByName[item];

  return acc;

  // return acc[item] = item;
}, {});
console.log(output)
// pluck/filter out by latest effectDates



//  EXPECTED OUTPUT
// { 
//   abc: [
//       { name: 'abc', effectiveDate: '2016-05-01T00:00:00+00:00' }
//   ],
//   abcd: [ 
//       { name: 'abcd', effectiveDate: '2016-09-01T00:00:00+00:00' }
//   ]
// }

2 个答案:

答案 0 :(得分:1)

如果你想要一个物体,我不知道你为什么要减少数组,可能会这样做:

tuple

http://jsbin.com/lawumineyu/edit?console

答案 1 :(得分:0)

按功能对任何数组进行排序,然后获取上次日期

~45us