3

I am creating a function that checks:

  1. If the array is empty, it should return undefined.
  2. If the property at the given key is not an array, it should return undefined.
  3. If there is no property at the key, it should return undefined.

So what I did is that I created an if statement using || operator to separate the cases:

function getFirstElementOfProperty(obj, key) {
  if(obj.key.length === 0 || !obj.key.isArray || !obj.key.hasOwnProperty(key)){
    return undefined;
  }else{
      return obj.key[0];
  }

}

var obj = {
  key: [1, 2, 4]
};

For some reason, this doesn't work. It also saying that "It Cannot read property 'length' of undefined".

Any idea what am I missing here?

  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Syntax – zerkms Jun 19 '17 at 23:44
  • You can also check does `obj` and `obj.key` exists. It looks like your `obj.key` is `undefined` – P.S. Jun 19 '17 at 23:49
  • Seems to me `Array.isArray(obj[key])? obj[key][0] : void 0` does the job. – RobG Jun 20 '17 at 00:12

1 Answers1

1
function getElem(obj, key){
    if (key in obj){
        if (Array.isArray(obj[key])){
            if (obj[key].length){
                return obj[key][0];
            }
        }
    }
    return undefined;
}

var obj = {key: [1, 2, 4], key2: []};
getElem(obj, "key")  // 1
getElem(obj, "key2")  // undefined
getElem(obj, "key3")  // undefined

Not a javascript expert, but I believe this works. If I recall correctly, javascript does not have short circuit evaluation, so you need to nest the if statements.

The outer checks if the key exists, second inner checks if it's an array, and most inner checks for the length. If it meets all of those, it returns the first element. Otherwise it returns undefined.

BrockLee
  • 931
  • 2
  • 9
  • 24