gloopit gloopit - 1 year ago 103
Javascript Question

indexOf but for objects?

I want to look through an object and assign each of it's existent properties to a variable.

There are 4 possible properties. Some of the objects have all 4. Some might only have two.

How can I check if a particular property exists? Is there an equivalent of indexOf() for arrays but for objects instead?

Answer Source

If you are only interested in properties set directly on the object (not accessible via the prototype chain) then hasOwnProperty will provide a boolean value, true, if an object has the specified property.

For example: testObject.hasOwnProperty('propertyToCheckFor') would return true if testObject.propertyToCheckFor exists, otherwise it would be false.

See the following code for a more expanded example:

var obj1 = {
  a: 1
var obj2 = {
  a: 1,
  b: 2
var obj3 = {
  b: 2,
  c: 3
var obj4 = {
  a: 1,
  b: 2,
  c: 3

// For dispaly purposes
document.write('<pre>' + JSON.stringify({
  obj1: {
    hasA: obj1.hasOwnProperty('a'),
    hasB: obj1.hasOwnProperty('b'),
    hasC: obj1.hasOwnProperty('c')
  obj2: {
    hasA: obj2.hasOwnProperty('a'),
    hasB: obj2.hasOwnProperty('b'),
    hasC: obj2.hasOwnProperty('c')
  obj3: {
    hasA: obj3.hasOwnProperty('a'),
    hasB: obj3.hasOwnProperty('b'),
    hasC: obj3.hasOwnProperty('c')
  obj4: {
    hasA: obj4.hasOwnProperty('a'),
    hasB: obj4.hasOwnProperty('b'),
    hasC: obj4.hasOwnProperty('c')
}, null, 2) + '</pre>');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download