Matthew Harwood Matthew Harwood - 1 month ago 7
Javascript Question

Are there any higher order function to return an object from an array of objects in javascript?

LIVE CODE EXAMPLE:



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

Question:

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:


  • immutability.

  • ease of testing.

  • learning purposes.



The 2 cases:


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

    {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:

    {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]}

Answer

Use 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]}