DEV Community

artydev
artydev

Posted on

The mappath function

Continuing to enhance our micro functional library, here is the mappath function.

mappath (propertypath, arrayofobjects) => arrayofpropertyvalues

Example :

let pets = [
  {
    petname : "Bill",
    breed : "poodle",
    weight: 12,
    owner : {
      ownername : "Paul",
      contribution : {
        amount : 32,
        payed : false
      },
      address : {
        city :  "Paris"
      }
    }
  },
  {
    petname : "Maya",
    race : "pointer",
    weight: 27,
    owner : {
      ownername : "Henri",
      contribution :  {
        amount : 12,
        payed : true
      },
      address : {
         city :  "London"
      }
    }
  },
  {
    petname : "Ooper",
    race : "setter",
    weight: 20,
    owner : {
      ownername : "Nicolas",
      contribution :  {
        amount : 12,
        payed : true
      },
      address : {
         city :  "London"
      }
    }
  }
]
Enter fullscreen mode Exit fullscreen mode

Let's retrieve all the amount values;


const amountpath = "owner.contribution.amount"

console.log(mappath(amountpath, pets))

Enter fullscreen mode Exit fullscreen mode

For me, that is more readable and testable, but that is a matter of taste.

Result :
Image description

You can play with demo here : DEMO

Top comments (0)