Search code examples
javascriptlodash

How to write it better way e.g. lodash


I want to check every child on way in array can i write it better with e.g. lodash

test[1] && test[1][2] && test[1][2][3] && doSomething

Solution

  • There are 3 common ways to get/check paths with lodash:

    1. _.get - which would attempt to get the value based on path and provide default if that value is not found

    2. _.has - which would give you boolean result if the path is found or not _.hasIn - which is like has but also would check if path is a direct or inherited property of object

    3. _.result - which would walk the path and execute any function among the way to get to the value or work as _.get otherwise (no functions present)

    var data = [
            [],
            [
              [],
              [
               'hello',
    	   function(){ return 'foo'}
              ]
            ]
        ];
    		
    console.log('get:', _.get(data, '1.1.0'))
    console.log('has:', _.has(data, '1.1.0'))
    
    console.log('result:', _.result(data, '1.1.0'))
    console.log('result:', _.result(data, '1.1.1'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

    The common thing here is all of them accept a path as a parameter which can do what you want. Just provide the deepest path and let those methods check/work for you.