Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate object with ramda.js path

I have a structure, like this

   [{
      title: "Section 1",
      items: [{
          title: 'Dashboard',
          icon: 'tachometer-alt',
          route: '/dashboard',
          opened: false
        },
        {
          title: 'Appointments',
          icon: 'calendar-alt',
          route: '/appointments',
          opened: true
        },
        {
          title: 'Orders',
          icon: 'box',
          route: '/orders',
          opened: false,
          children: [{
            title: 'Orders submenu 1',
            route: '/orders/sub1',
            opened: false,
            children: [{
              title: 'Orders submenu 1 subsubmenu 1',
              route: '/orders/sub1/sub1sub1'
            }]
          }]
        }
      ]
    }]

These are basically sections with menu items and every menu item could contain submenus, submenus have subsubmenus, etc.

I have a toggle function, which is getting a property array. I want to negate the variable that is "marked" by this array, so when I am getting an [0, 'items', 2, 'children', 0, 'opened'] array, the expected behaviour would be that the "Orders submenu 1" has its "opened" property set to "true".

The property indexer array is alterable too, so I can tweak that a little bit, if needed.

With Ramda, i can easly get the current value with R.path([0, 'items', 1, 'opened'], menu) but how can I set it to "true"?

Jsfiddle for example: https://jsfiddle.net/hurtonypeter/1tm4wcuo/

like image 997
Peter Hurtony Avatar asked Apr 16 '26 02:04

Peter Hurtony


1 Answers

You can make use of lenses in Ramda to achieve this.

const togglePath = (path, obj) => R.over(R.lensPath(path), R.not, obj)
togglePath([0, 'items', 1, 'opened'], menu)
like image 134
Scott Christopher Avatar answered Apr 17 '26 15:04

Scott Christopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!