DEV Community

artydev
artydev

Posted on

Using our functional utilities for retrieving deep nested properties.

Let's see a practical case of our tiny functional toolbox.

Here, the object we will use :

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

Say you want the list of all the cities.

With our tools, we can create a function which, when given a 'string path' for a property, returns the property value.

Let's name this function pick.

Here is a possible implementation :


function pick (path) {
  let pickprops =  map((prop) => pickprop(prop), path.split("."));
  return pipe(...pickprops);
}


Enter fullscreen mode Exit fullscreen mode

We can now create a function, which will return a 'city value' for a single entry.


let pickCity = pick("owner.address.city");

Enter fullscreen mode Exit fullscreen mode

Nice isn't it ?

Now we can explicitely list all the cities :


let pickCity = pick("owner.address.city");


let cities = map(pickCity)(pets);

// or

cities =  map(pickCity, pets);

console.log(cities)

Enter fullscreen mode Exit fullscreen mode

I like this one too :


let cityMapper = map(pick("owner.address.city"));

let cities = cityMapper(pets);

console.log(cities)

Enter fullscreen mode Exit fullscreen mode

We can go a step further and feel the spirit of functional programming :


let mapper = compose(map, pick);

let citymapper = mapper("owner.address.city")

cities = citymapper(pets)

console.log(cities)

Enter fullscreen mode Exit fullscreen mode

Result :

Image description

You can play with a demo here Demo

Hope you enjoyed...

Top comments (0)