allencoded
allencoded

Reputation: 7275

Checking if a dynamic property exists in a javascript array

I have code that dynamically adds properties to an array.

data.tagAdded[tag.Name] = {
                    tag: tag,
                    count: 1,
                };

Later in my code I need to check rather data.tagAdded has properties. If it doesn't have properties I need to do some other code. The problem is I can't figure out how to check for the existence properties.

The tagAdded = [] is always an array rather it contains properties or not, so I can't check if it is null. I can't say if property because I don't know the name of the property since it is dynamic. I can't check length because an array with properties is of length 0.

Any other way to check if properties exist?

Upvotes: 0

Views: 1127

Answers (2)

HieuHT
HieuHT

Reputation: 469

You can try

for (var prop in tagAdded) {
    if (tagAdded.hasOwnProperty(prop)) {
        console.log("property exists");
    }
}

Upvotes: 0

wvandaal
wvandaal

Reputation: 4295

Assuming you just want to see if you've assigned any key-value pairs to your associative array (just FYI, for what you're doing, an object might serve you better), you can do the following:

function isEmpty(o) {
  return !Object.keys(o).length && !o.length;
}

var x = [];
isEmpty(x);
=> true

x['foo'] = 'bar';
isEmpty(x);
=> false

delete x.foo;
isEmpty(x);
=> true

x.push(1);
isEmpty(x);
=> false

Upvotes: 1

Related Questions