背景
尝试学习javascript的高阶函数,一些redux理论,并通过数据转换示例应用它,并且在过去的几个小时内都失败了。 :(
问题:
如何迭代approved1
或approved2
并返回基于 2个案例的新对象。此外,有没有办法使用更高阶函数(如Array.reduce()
)或高阶函数中的组合来执行此操作? 最后,如果最终的Object包装在一个很好的数组中。
我想要这个有几个原因:
2例:
如果所有 dateApproved
值均为!== null
(在此示例中为:approval1
数组),则返回一个新的Object (或数组)包装对象)看起来像:
{type: 'APPROVED', approvals: [...approved1]}
如果 dateApproved
值的任何等于null
(在此示例中为:approval2
数组),则返回一个新的对象 (或Array wrapped Object),如下所示:
{type: 'PENDING', approvals: [...approved2]}
JAVASCRIPT:
// With given logic this array evaluate with a type of 'APPROVED'
var approved1 = [
{
dateApproved: new Date(),
id: 1,
},
{
dateApproved: new Date(),
id: 2,
}
];
// With given logic this array evaluate with a type of 'PENDING'
var approved2 = [
{
dateApproved: null,
id: 1,
},
{
dateApproved: new Date(),
id: 2,
}
];
// This reducer does nothing proper right now just placeholder.
function isApproved(previousValue, currentValue, currentIdx) {
var TYPE = ['APPROVED', 'PENDING'];
if(previousValue.dateApproved !== null && currentValue.dateApproved !== null) {
return currentValue
}
}
var x = approved1.reduce(isApproved);
console.log(x); // LOG: {type: 'APPROVED' approvals: [...approved1]}
var y = approved2.reduce(isApproved);
console.log(x); // LOG: {type: 'PENDING' approvals: [...approved2]}
答案 0 :(得分:3)
function wrap(approvals) {
return {
type: approvals.every(a => a.dateApproved != null) ? 'APPROVED' : 'PENDING',
approvals: approvals
};
}
wrap(approved1);
// => Object {type: "APPROVED", approvals: Array[2]}
wrap(approved2);
// => Object {type: "PENDING", approvals: Array[2]}