0

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?

1
  • Are you just trying to see if your array object has had any elements assigned to it or do you need to see if a specific key has a value associated with it? Commented May 15, 2014 at 14:54

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.