-1

i would like to know how to loop all of my sql datas (that i parsed into a json table) into an array, with adding a key to each of them.

I know how i can loop all of the data into an simple string like this :

var dbString ="";
for(i = 0; i < result.response.length; i++) 
{
    dbString += result.response[i].names;
}

This would just look like this

var dbString = "James Michael Alfred....";

But how can i make this look like this :

var dbString = {"James":1, "Michael":2, "Alfred":3, .....}

Thanks.

randomcat
  • 17
  • 6

1 Answers1

0

It's a really unique demand to organise a list of names like you want, but here it is:

var dbString = {};
var names = result.response;
for(var i = 0; i < names.length; i++){
    dbString[names[i]] = i + 1;
}
bugovicsb
  • 422
  • 1
  • 7
  • 15
  • I'll try that in a few minutes, thanks for the answer – randomcat Sep 10 '17 at 15:18
  • It is working so far, but i have a problem, the array is not sorted by the keys. Its like { alfred : 4, michael : 1, James: 5, .... } – randomcat Sep 12 '17 at 07:58
  • objects like `{"alfred": 4, "michael": 1, ...}` cannot be sorted , you can use arrays for that like `["michael", "alfred, ...]` and access elements by index (e.g. `array[0]` -> "michael") – bugovicsb Sep 13 '17 at 09:14
  • What is did was, just changing the places so it easily loops the "i". `dbString[i+1] = names[i];` – randomcat Sep 13 '17 at 09:21
  • that is almost like an array (except that an array is zero-based). why do you insist on using object instead of an array? – bugovicsb Sep 13 '17 at 09:37