1

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')?

user2456977
  • 3,830
  • 14
  • 48
  • 87
  • 1
    `_.has(object, path)` `<-` did you read the word `path`? basically, lodash will traverse the object using that path. – Ele Oct 22 '18 at 16:50
  • 1
    also, it's possible that the `"0"` value is treated as `false` instead of the number 0. Finally, your value for length is also being treated like a string, which could cause subtle casting problems as well – Josh E Oct 22 '18 at 16:53
  • Ah i get it thanks .. Yea unfortunately I'm getting these values from the backend so I need to parse the string values – user2456977 Oct 22 '18 at 16:57

2 Answers2

3

_.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>
Ele
  • 33,468
  • 7
  • 37
  • 75
0

You can use _.at() to pluck the values from the object, and than compare the result's length with the original number of keys:

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

const hasKeys = (obj, keys) => _.eq(_.at(obj, keys).length, keys.length);

console.log(hasKeys(values, ['page', 'length']));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209