Skip to main content
1-Visitor
May 5, 2020
Solved

Code Snippet to check if any property already exist in thing

  • May 5, 2020
  • 1 reply
  • 5432 views

Hi,

 

I want to check whether any property already exists in thing or not, if not then I will create a new property using AddPropertyDefinition.

 

Please provide the code snippet for this property existence check.

 

Thanks in advance.

Best answer by smainente

Some options :

 

1. Just set the property value without checking if it exists and handle the exception to create it if it does not exist.

 

2. Otherwise you have the JS service GetPropertyDefinition. Are you looking at properties defined on the Thing itself or also properties inherited from Thing Shape and Template ?

 

3. Finally, not al the public ThingWorx APIs are exposed as JS Service. The Java extension SDK exposes methods such as hasProperty, hasPropertyDefinition, .... in Thing.

1 reply

16-Pearl
May 5, 2020

One approach would be to use GetPropertyDefinitions and then loop through the infotable returned by it.

var propertyTable = me.GetPropertyDefinitions({
category: undefined /* STRING */,
type: undefined /* BASETYPENAME */,
dataShape: undefined /* DATASHAPENAME */
});

var result = false;
var tableLength = propertyTable.rows.length;
for (var x=0; x < tableLength; x++) {
var row = propertyTable.rows[x];
if(row.name === 'temperature'){
result = true;
break;
}
}

 

 

ranjank1-VisitorAuthor
1-Visitor
May 5, 2020

Hi @rjanardan ,

 

In my opinion, this is not a good approach because there are already many default properties and for my use-case, if the property encountered is not present then I have to create a new property (and if present just update its value). The no of properties that I have to create is more than 30.

 

Unnecessary looping will make the service slower. It would be better if any API is present that would take "propertyName" as input and just return "true or false" after checking its existence.

 

Pls guide.

smainente16-PearlAnswer
16-Pearl
May 5, 2020

Some options :

 

1. Just set the property value without checking if it exists and handle the exception to create it if it does not exist.

 

2. Otherwise you have the JS service GetPropertyDefinition. Are you looking at properties defined on the Thing itself or also properties inherited from Thing Shape and Template ?

 

3. Finally, not al the public ThingWorx APIs are exposed as JS Service. The Java extension SDK exposes methods such as hasProperty, hasPropertyDefinition, .... in Thing.