Software Costa Rica Software Costa Rica - 3 months ago 15
Javascript Question

JSON Firebase URL to Array

I need to get as array a firebase link. I have the following link https://.firebaseio.com/users.json which is going to retrieve the following json file:

{
"-KOIbPUxKWKMaIOuX1cR": {
"email": "fillocj.rc@gmail.co",
"lastName": "Alberto",
"password": "password",
"userName": "Rodolfo"
},
"-KOOF5S3kDnvsT9nVx85": {
"email": "test@test2.com",
"lastName": "TEST",
"password": "password",
"userName": "TEST"
}
}


and I am using the following function in javascript to get make a conversion:

var o = 'https://<myInstance>.firebaseio.com/users.json';
var arr = Object.keys(o).map(function (k) { return o[k] });
console.log(arr)


But the result if this function is the following:

Array[53]

0:"h"
1:"t"
2:"t"
3:"p"
4:"s"
5:":"
6:"/"
7:"/"
8:"a"
9:"g"
10:"u"
11:"l"
12:"a"
13:"r"
14:"f"
15:"i"
16:"r"
17:"e"
18:"d"


And of course this is not what I need, I need to retrieve all emails or all users or all id numbers. Is there any way to retrieve that? Or can somebody help me out with a piece of code which can help me with.

Thanks in advance.

Answer

You can use jQuery map function to map objects.

$.map(source, function(item, i){
    return source.email; //return what you want
});

If you just want to retrieve the json content from the url you need to make an AJAX request. A simple way of doing this is using getJSON function.

    $.getJSON("https://<myInstance>.firebaseio.com/users.json", function(result){
        // here you get the JSON content
    });

Take a look at this snippet:

window.users = {
    "-KOIbPUxKWKMaIOuX1cR": {
        "email": "fillocj.rc@gmail.co",
        "lastName": "Alberto",
        "password": "password",
        "userName": "Rodolfo"
    },
    "-KOOF5S3kDnvsT9nVx85": {
        "email": "test@test2.com",
        "lastName": "TEST",
        "password": "password",
        "userName": "TEST"
    }
};



function getEmails(users){
  return $.map(users, function(item, i){
  	return item.email;
  });
};

function getSampleObject(users){
  return $.map(users, function(item, i){
      return {
        email: item.email,
        username: item.userName
      };
    });
};

$(window).ready(function(){
  var emails, users;
  
  emails = getEmails(window.users);
  users = getSampleObject(window.users);  
  
  $('#output_1').text(JSON.stringify(emails));
  $('#output_2').text(JSON.stringify(users));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Retrieves email</h2>
<code id="output_1"></code>
<hr />
<h2>Retrieves object</h2>
<code id="output_2"></code>