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.
Consideration on consideration: arrays are also objects and
hasOwnPropertyworks with them in the same way -> https://ideone.com/gUT8N5 :-)– hkotsubo