[英]Are there any higher order function to return an object from an array of objects in javascript?
Background: 背景:
Trying to learn javascript's higher order function, some redux theory and applying it through a data transformations example and have been failing for the last few hours. 试图学习javascript的高阶函数,一些redux理论并通过数据转换实例应用它,并且在过去的几个小时里一直在失败。 :( :(
Question: 题:
How can I iterate over the approved1
or approved2
and return a new object bases on 2 cases . 如何迭代approved1
或approved2
并返回基于2个案例的新对象。 Furthermore, is there a way to do this with a higher order function like Array.reduce()
or a combination baked in higher order functions? 此外,有没有办法用更高阶函数(如Array.reduce()
或高阶函数烘焙的组合Array.reduce()
执行此操作? Lastly , if the final Object is wrapped in an array thats fine too. 最后 ,如果最终的Object被包装在一个很好的数组中。
I want this for a few reasons: 我想要这个有几个原因:
The 2 cases: 2例:
If all dateApproved
values are !== null
(in this example: approval1
array) then return a new Object (or Array wrapped Object) which looks like: 如果所有 dateApproved
值都是!== null
(在此示例中为: approval1
数组),则返回一个新的Object (或Array wrapped Object) ,如下所示:
{type: 'APPROVED', approvals: [...approved1]}
If any of the dateApproved
values are equal to null
(in this example: approval2
array) return a new Object (or Array wrapped Object) which looks like: 如果任何 dateApproved
值等于null
(在此示例中为: approval2
数组),则返回一个新的Object (或Array wrapped Object) ,如下所示:
{type: 'PENDING', approvals: [...approved2]}
JAVASCRIPT: 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]}
Use Array.prototype.every : 使用Array.prototype.every :
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]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.