简体   繁体   中英

I am getting a TypeError for using the 'in' keyword on an object?

I am attempting to write a helper function for myself to check if a property is inside of a given OBJECT. For my own use case, if I come across an array, then I only have to obtain the first (0 index) array to continue. My helper function is to return a boolean value since it is only checking to see if the provided string will work (or not).

Given the OBJECT:

{'object': {
        "promotion": {
            "items": [{
                "startAndEndDate": {
                    "startDate": "2017-11-10",
                    "endDate": "2017-11-29"
                },
                "amount": {
                    "discount": 12
                }
            }]
        }
    }
};

My function:

var propertyInObjectFuncUtil = function (string, obj) {
            var substringArray = string.split('.');

            if (substringArray.length) {
                try {
                    substringArray.reduce(function (prev, curr) {
                        if (curr in prev) {
                            return prev[curr];
                        } else if (curr in prev[0]) {
                            return prev[0][curr];
                        } else {
                            throw ('These are not droids you are looking for...');
                        }
                    }, obj);

                    return true;
                } catch (error) {
                    console.error(error);
                    return false;
                }

            }
        };

Attempting to make it work with the following:

var example1 = propertyInObjectFuncUtil('object.promotion.items.amount.discount',obj) // true
var example2 = propertyInObjectFuncUtil('object.promotion.itemss',obj) // false
var example3 = propertyInObjectFuncUtil('object.promotion.items.startAndEndDate.endDates',obj) //false

However I am getting this TypeError: TypeError: Cannot use 'in' operator to search for 'itemss' in undefined

As the error message says, the in operator cannot be used when the right hand side is undefined , it only works on objects. So add a check for those:

if (Object(prev) === prev && curr in prev) {
    return prev[curr];
} else if (Array.isArray(prev) && Object(prev[0]) === prev[0] && curr in prev[0]) {
    return prev[0][curr];
} else {
    throw new Error('These are not droids you are looking for...');
}

itemss witten with 2 's' does not exist, you cannot iterate over an undefined value.

add a check for null/undefined and you should be fine.

Your issue occurs when you use an invalid path. If your path is invalid, then curr in obj will be false , thus making you check the next condition. Your first example is working fine, however, your others are not. Consider the values of prev over multiple iterations for the path:

'object.promotion.itemss'

First, prev starts off as:

{
  'object': {
    "promotion": {
      "items": [{
        "startAndEndDate": {
          "startDate": "2017-11-10",
          "endDate": "2017-11-29"
        },
        "amount": {
          "discount": 12
        }
      }]
    }
  }
}

You then check if 'object' is in this object, which is it, so you update prev.

Next iteration your prev is now:

{
  "promotion": {
    "items": [{
      "startAndEndDate": {
        "startDate": "2017-11-10",
        "endDate": "2017-11-29"
      },
      "amount": {
        "discount": 12
      }
    }]
  }
}

You then check to see if 'promotion' is in this object using the first condition of your if, it is, so you update prev.

Third iteration, prev is now:

{
  "items": [{
    "startAndEndDate": {
      "startDate": "2017-11-10",
      "endDate": "2017-11-29"
    },
    "amount": {
      "discount": 12
    }
  }]
}

You now first check to see if 'itemss' is in this object using your first condition in your if. It is not. So you then check your second condition:

} else if (curr in prev[0]) {

The issue is here. prev[0] is trying to access key 0 in your prev object (shown above), however, this key doesn't exist, so prev[0] evaluates to undefined . Using curr in undefined will throw an error as this isn't a valid use case of in . Consider checking if prev[0] is defined (and an object) before using it with the in operator, as shown in this answer

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