Skip to main content
Apr 16, 2020 8:25 PM UTC
Solved

Using forEach to iterate through data being pulled from JSON in infotable

I am getting an issue saying 'for each is only available in Mozilla JavaScript extensions (use moz option)'. I am trying to add rows to my infotable using data being pulled in from a JSON file. 

 

Is there another way to do this? Thanks!

Apr 28, 2020 11:41 AM UTC

data.array[i].isbn ended up working for me, thank you!

7 replies

Apr 17, 2020 8:30 AM UTC

for each should work in Twx, even if not, you can change to use for (i<row) command to iterate the data

Apr 17, 2020 9:25 AM UTC

Yes, Ryan is correct, ThingWorx uses Rhino JS Engine thus supports for each

Apr 17, 2020 5:59 PM UTC

Hi @morganweiss33.

 

Try changing this row:  for (var i=0; i < data.rows;i++) {

to:  for (var i=0; i < data.array.length;i++) {

 

Refer to this article for more information.

 

Regards.

 

--Sharon

 

Apr 27, 2020 7:07 PM UTC

Hi @morganweiss33.

 

If one of the previous responses answered your question, please mark the appropriate one as the Accepted Solution for the benefit of others with the same question.

 

Regards.

 

--Sharon

Apr 27, 2020 8:48 PM UTC

Hello @morganweiss33,

 

tl;dr Use for(var i = 0..... as @slangley suggests.

 

ThingWorx infotables look like JavaScript arrays, but they are not. You can use forEach and its friends, but to do it you have to wrap infotable rows into js Array explicitly like that:

var nativeArray = Array.from(myInfotable);

 

Here's a very useful (!) example of this technique, which randomly disables half of your GenericThings:

var result = 'Disabled ' + Array.from(ThingTemplates["GenericThing"].QueryImplementingThings({ maxItems: 100000 }))
	.map(t => Things[t.name])
	.filter(t => {
		if (Math.random() < 0.5 && t.IsEnabled()) {
			t.DisableThing();
			return true;
		} else {
			return false;
		}
	}).length + ' things';

 

That looks cool, but apparently it requires some data copying (sadly Rhino !== V8) and thus works slower than for-based approach straight from ALGOL. I don't remember the right figures, but for me it was something like twice slower, on that scale.

 

Regards,
Constantine

morganweiss33AuthorAnswer
Apr 28, 2020 11:41 AM UTC

data.array[i].isbn ended up working for me, thank you!