Search code examples
javascriptobjectkeylodash

Lodash: _.has check for keys returning false


I have this object:

values = {page: "0", length: "12"}

I want to check if the keys have page and length so I came up with this solution using Lodash:

has(values, 'page') && has(values, 'length')

This return true as expected but I wanted to use a more shorthand approach and tried:

has(values, ['page', 'length]') but this returns false. Any idea why?

https://lodash.com/docs/4.17.10#has

Lodash has an example where this returns true:

var object = { 'a': { 'b': 2 } };

_.has(object, 'a');
// => true

_.has(object, 'a.b');
// => true

_.has(object, ['a', 'b']);
// => true

Is there a more elegant way to check for the keys in my object or should I just keep my solution the way it is: has(values, 'page') && has(values, 'length')?


Solution

  • _.has(object, path) <- did you read the word path? basically, lodash will traverse the object using that path.

    I think you can use vanilla javascript for doing that:

    let values = { page: "0", length: "12" },
        keys = Object.keys(values),
        result = ['page', 'length'].every(k => keys.includes(k));
        
    console.log(result);

    Using lodash:

    let values = { page: "0", length: "12" },
        keys = _.keys(values),
        result = _.every(['page', 'length'], k => _.includes(keys, k));
            
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>