How to check if there is a property in an object?

Asked

Viewed 139 times

4

I am pulling a back-end user on my front end. How do I check if a property exists in the object usuario?

Ex:

let usuario = {
  id: "1",
  name: "Jose",
  options: {
    channel: "1",
    reference: "a"
  },
  finished: "20/01/2021"
}

In case only some users would have the property finished, but how would I check whether a usuario has this property?

I thought about user.finished === true, but it obviously didn’t work. I’d also need to check in case the usuario had not (so I thought true, in case you needed one usuario without this property I would put false).

2 answers

3

Consideration of the title

The title of the question is how to check if there is a property in the array?, but the type shown in the question is not a Array, and yes a Object.

Solution 1

Maybe you can check it with typeof.

Behold:

var user_1 = {
 id: "1",
 name: "Jose",
 options: {
  channel: "1",
  reference: "a"
 },
 finished: "20/01/2021"
}

var user_2 = {
 id: "1",
 name: "Jose",
 options: {
  channel: "1",
  reference: "a"
 }
}


console.log(typeof user_1.finished === 'undefined' ? 'Não possui' : 'Possui')
console.log(typeof user_2.finished === 'undefined' ? 'Não possui' : 'Possui')

typeof will return the variable type. For undefined values, typeof returns a string with the value 'Undefined'`.

Solution 2

Also, you can use the method hasOwnProperty. This method is available at Object javascript.

Example:

var user_2 = {
   id: "1",
   name: "Jose",
   options: {
    channel: "1",
    reference: "a"
   }
}

console.log('Tem nome? %s', user_2.hasOwnProperty('name'))
console.log('Tem finished? %s', user_2.hasOwnProperty('finished'))

HasOwnProperty check whether the property has been set or not. In this case, if the value is false, will also return true for hasOwnPropery, since it checks whether the property is defined, and not whether the value is empty or something like.

Solution 3

You can also convert the value of finished for Boolean. In this case, instead of checking if the property exists, it will convert the value to true or false, depending on the content present.

console.log(!!user.finished);

In the above example, if user.finished is not defined, has value as 0, null or '', will return false also. If you have something filled in, with in the example of the date placed in your question, you will return true.

Then it would be enough:

if (!! user.finished) {
    // Valor existe
}

Note: When calling a nonexistent property of an object in Javascript, it usually returns undefined. If you have the variable var user = {id: 1} and call console.log(user.name), will be returned undefined.

  • 4

    Consideration on consideration: arrays are also objects and hasOwnProperty works with them in the same way -> https://ideone.com/gUT8N5 :-)

3


In doing user.finished === true, you are checking if the value of the "finished" property is true, not if it exists.

To do what you want, an alternative is to use hasOwnProperty, passing the name of the property:

var user = {
    id: "1",
    name: "Jose",
    options: {
        channel: "1",
        reference: "a"
    },
    finished: "20/01/2021"
};

if (user.hasOwnProperty('finished')) {
    console.log('User tem propriedade finished');
} else {
    console.log('User não tem propriedade finished');
}


They’ll probably suggest to just test like this:

if (user.finished) {
    console.log('User tem propriedade finished');
}

The problem is that it will false if the property exists but has a falsifiable value:

var user = {
    id: "1",
    name: "Jose",
    options: {
        channel: "1",
        reference: "a"
    },
    finished: ""
};

if (user.finished) {
    console.log('User tem propriedade finished');
} else {
    console.log('User não tem propriedade finished');
}

Note the example above that the property finished exists, but since its value is the empty string (which is considered "false"), the code enters the else.


They may even suggest that you check whether the value is undefined, but falls into the same problem: if it exists and the value is in fact undefined, will also be deemed not to exist.

See the difference:

var user = {
    id: "1",
    name: "Jose",
    options: {
        channel: "1",
        reference: "a"
    },
    finished: undefined
};

if (user.finished) {
    console.log('User tem propriedade finished');
} else {
    console.log('User não tem propriedade finished');
}

if (user.finished !== undefined) {
    console.log('User tem propriedade finished');
} else {
    console.log('User não tem propriedade finished');
}

if (typeof user.finished !== "undefined") {
    console.log('User tem propriedade finished');
} else {
    console.log('User não tem propriedade finished');
}

if (user.hasOwnProperty('finished')) {
    console.log('User tem propriedade finished');
} else {
    console.log('User não tem propriedade finished');
}

In this case, the value of the property is undefined. The first 3 tests consider that the property does not exist (although it exists, the problem is that undefined is a considered value false, and so the first enters the else, and to be undefined, the following 2 also enter the else - only the last with hasOwnProperty actually checks if the property exists, regardless of the value).

  • I did that and it worked!!!! However I can’t do a check, it has some property of notownproperty type ?

  • 2

    @Luckdev just invert the boleana expression with ! user.hasOwnProperty('finished')

  • @Luckdev As I’ve been told: if (! user.hasOwnProperty('finished')) { não tem a propriedade } - any boolean condition can be "reversed" with the use of !

  • IT WORKED!!! Thank you very much, I had to adapt some things because what I was doing was very different, but that’s exactly what I needed. (and I traveled nice, I thought about using ! but I thought about the possibility of there being a property ) THANK YOU VERY MUCH!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.