有没有更高阶的函数从javascript中的对象数组返回一个对象? [英] Are there any higher order function to return an object from an array of objects in javascript?

查看:206
本文介绍了有没有更高阶的函数从javascript中的对象数组返回一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

尝试学习javascript的高阶函数,一些redux理论,并通过数据转换示例应用它,在过去几个小时里一直都失败了。 :(

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. :(

问题:

如何迭代 approved1 approved2 ,并返回一个基于 2个的新对象,此外,有没有办法使用更高级的函数,如 Array.reduce()或在较高阶函数中组合的组合?最后,如果最终的对象被包装

How can I iterate over the approved1 or approved2 and return a new object bases on 2 cases. Furthermore, is there a way to do this with a higher order function like Array.reduce() or a combination baked in higher order functions? Lastly, if the final Object is wrapped in an array thats fine too.

我想要这个原因有以下几点:

I want this for a few reasons:


    <
  • 易于测试

  • 学习目的

2例:


  • 如果全部 dateApproved 值是!== null (在这个例子中: approval1 array)然后返回一个新的Object (或Array wrapped Object),如下所示:

  • If all dateApproved values are !== null (in this example: approval1 array) then return a new Object (or Array wrapped Object) which looks like:

{type :已批准,批准:[... approved1]}

如果 dateApproved 中的任何值等于 null (在本示例中为 approval2 array)返回一个新的Object (或Array wrapped Object),如下所示:

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:

{type:'PENDING',approval:[... 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]}


推荐答案

使用数组。 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]}

这篇关于有没有更高阶的函数从javascript中的对象数组返回一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆