هل تعلم بوت Libre كما يوفر الآلهة 3D مجانا على شبكة الإنترنت الكلام API ؟
Self, AIML, and scripting

Loop on array of objects

قبل gioking نشر Mar 12 2018, 7:00

Hi, I have a question, I'm building a bot that have to call a rest service made by me, the service response is a List of json objects but at the moment I can get only the first element of the array eg. array[0].Name ecc...

My ask is: how can I loop the array to have the following formatted data ?

Name: Pluto

Surname: Paperino

ecc...

this is my method:

function getpersons() {
debug(star);
var result = Http.requestJSON("http://endospore.xxxx.com:85/api/Data/GetPersons");

//var person = result[0].Name + " " + result[0].Surname;

var text = "Persons are: ";
for (i = 0; i < result.length; i++) {
text = text + person[i] + "<br>";
}
return text;
}

Thanks


by admin posted Mar 12 2018, 12:44

There are a few ways to iterate over an array.
In your code use result.length() not result.length

1
2
3
4
5
6
7
8
var result = Http.requestJSON("http://endospore.xxxx.com:85/api/Data/GetPersons");
var text = "Persons are: ";
for (i = 0; i < result.length(); i++) {
  var person = result[i].Name + " " + result[i].Surname;
  text = text + person + "<br>";
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can also use,

1
2
3
4
5
6
7
var result = Http.requestJSON("http://endospore.xxxx.com:85/api/Data/GetPersons");
var text = "Persons are: ";
for (person in result) {
  text = text + person.Name + " " + person.Surname + "<br>";
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Or to iterate over an array's elements, or any attribute set of an object use,

1
2
3
4
5
6
7
var result = Http.requestJSON("http://endospore.xxxx.com:85/api/Data/GetPersons");
var text = "Persons are: ";
for (person in result.element) {
  text = text + person.Name + " " + person.Surname + "<br>";
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Updated: Mar 12 2018, 12:47
Thumbs up: 0, thumbs down: 0, stars: 0.0
Views: 3065, today: 2, week: 4, month: 14

معرف: 21312132
Tags: loop array
نشر: Mar 12 2018, 7:00
تحديث: Mar 12 2018, 12:45
الردود: 1
الآراء: 3109, اليوم: 2, الأسبوع: 2, الشهر: 18
0 0 0.0/5