简体   繁体   中英

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/

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM