How to add an object as a data attribute - javascript

Using the api I was able to retrieve the info i needed trough the following endpoints and create the following object.
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
}
<datagrid id = "topicGrid" data='[{}]'>
<datagrid-column head="Topic" content-key="name"></datagrid-column>
<datagrid-column head="Followers" content-key="followers"></datagrid-column>
<datagrid-column-time head="Created" content-key="created" format="date"></datagrid-column-time>
<datagrid-column-time head="Updated" content-key="updated" format="date"></datagrid-column-time>
</datagrid>
I would like to somehow append the "lego" object in the new data attribute ?
Now i tried something like
setAttribute("data", lego); but my knowledge here is limited.
Any help is apreciated. Thank you.
Update:
I tried passing the object as a string but I only get the last element of the object. Kind of like it's looping trough the whole object and stopping at the last one.
$('datagrid').attr('data', JSON.stringify(lego));
My solution
$.get( "..." ).done(function( data ) {
var legoArr = []
$.each(data.topics, function(index,item) {
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
};
legoArr.push(lego);
});
$('datagrid').attr('data', JSON.stringify(legoArr));
});

Related

Retrieve data from Firebase using Google Apps Script

I'm developing a Google Spreadsheet to manage reservations for a hotel. It has two main tabs. One of them is used to make the reservations and the other one is used to make queries to the reservations already made. I managed to make it work just fine with the built-in tools of google apps script using a tab as database.
I'm trying to export my data to a Firebase database, but I cannot find how to fetch some information I need. My data is stored using a code generated using the date of the reservation as integer format + the name of the person without spaces. This is the JSON generated by firebase:
{
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
}
}
My question is: let's suppose I want to know all the reservations made for the day 01/March/2021, what is the code for me to look inside the objects and then, if they match my search, get the info I need?
I converted the JSON to an array of objects, then filtered by date. Added the console logs to check if everything is right. You can see the logs when you go to view -> executions in your script. Click on the function execution to see the logged objects.
function myFunction() {
var a ={
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
},
"44256002ÍcaroNovodeOliveira" : {
"code" : 44256002,
"date" : "2021-04-01T03:00:00.000Z",
"name" : "Ícaro Dovo de Oliveira"
}
};
var values_a = Object.values(a);
var keys_a = Object.keys(a);
var array_a = keys_a.map((item, index)=> {return {"key": item, "values": values_a[index]};});
console.log(array_a);
var filter_date = "2021-03-01T03:00:00.000Z";
var filtered_a=array_a.filter(item => {return item.values.date === filter_date;})
console.log(filtered_a);
}
Thank you for your help! But my point was actually a little bit different, maybe I wasn't so clear.
While trying to explain it to you, I found the answer to my question. It was right under my nose this whole time and I didn't notice it. Here is the solution I needed:
First, I have to assign a rule to my firebase telling it what element I will be working on, so if I want to find reservations based on the date, it would look like this:
{
"rules": {
".read": true,
".write": true,
".indexOn":["date"]
}
}
Then, back to my script, it will be like:
function getReservations() {
var ss = SpreadsheetApp.getActive().getSheetByName('Search');
var date = ss.getRange('C11').getValue();
var firebaseUrl = "https://script-examples.firebaseio.com/";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var queryParameters = {orderBy:"date", equalTo: date};
var data = base.getData("", queryParameters);
for(var i in data) {
Logger.log(data[i].code, data[i].name, data[i].date);
}
}
The log retrieves:
[20-12-08 11:30:33:696 BRT] 44256001 Larissa Meimberg Baraldi 2021-03-01T03:00:00.000Z
[20-12-08 11:30:33:698 BRT] 44256001 Ícaro Novo de Oliveira 2021-03-01T03:00:00.000Z
This information was described on the documentation here:
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase/tutorials/read-and-write-data-in-firebase-from-apps-script
I think I got a little overwhelmed with the amount of information I got and skipped this part of the tutorial.
Thank you so much for your time and help.

getting the key/pair values out of an object that in an object

Objects thats returned:
ref.orderByChild('name').once('value').then(function(snapshot){
var results = snapshot.val();
When i log results the image is what i get, Ive been trying to access the value of 'active' for each of the three objects, phishing, information and techniques.
This is my first JS application sorry if its an easy one but couldn't find an answer else where that worked.
There are two (common) ways to do this: the Firebase way and the regular JavaScript way.
the Firebase way
Since it seems you're returning a list of nodes, I'll start with the Firebase way.
ref.orderByChild('name').once('value').then(function(snapshot){
var actives = {};
snapshot.forEach(function(childSnapshot) {
var result = childSnapshot.val();
var key = result.key;
var active = result.active;
actives[key] = active;
}
console.log(actives);
}
So we're using Firebase's Snapshot.forEach() method here to loop over the child nodes.
the regular JavaScript way
Alternatively you can get the value of the entire snapshot as you already do and use plain old JavaScript to get the result you need. Jatin's answer shows one way to do that, but here's another:
ref.orderByChild('name').once('value').then(function(snapshot){
var results = snapshot.val();
var keys = Object.keys(results); // ["information", "phishing", "techniques"]
var actives = {};
keys.forEach(function(key) {
actives[key] = results[key].active;
});
console.log(actives);
}
So in this case we're using Object.keys() to get the child node names and then loop over that array with JavaScript's Array.forEach().
var snapshot = {
"information" : {
"active" : "y",
"name" : "information"
},
"phishing" : {
"active" : "z",
"name" : "phishing"
},
"techniques" : {
"active" : "x",
"name" : "techniques"
},
};
console.log(snapshot.information.active);
console.log(snapshot.phishing.active);
console.log(snapshot.techniques.active);

MongoDB, PHP and JavaScript

I have the following document in a MongoDB 2.0.4 and PHP 5.5*
{
"children" : [
{
"name" : "openGL::gl"
},
{
"name" : "openGL::interfaces"
},
{
"name" : "openGL::picking"
},
{
"name" : "openGL::objects"
}
],
"name" : "test"
}
Using php I want to create another collection having a copy of this document.Because I cannot use php mongo::command I am just getting a cursor for the first collection and insert this cursor into the second:
$cursor = $collection->find();
foreach($cursor as $document){
$result->insert($document);
};
$collection is the original and $result is the new one.
Now the strange thing is sometimes this works perfectly and sometimes I recieve the following:
{
"children" : {
"3" : {
"name" : "openGL::objects"
},
"0" : {
"name" : "openGL::gl"
},
"1" : {
"name" : "openGL::interfaces"
},
"2" : {
"name" : "openGL::picking"
}
},
"name" : "test"
}
And this is really bad because I am trying to get those infos into Javascript and therefore the first one (the original) is an Array whereas the second one is an object with properties.
Does somebody know why I get this and how to fix it?
So this is the solution I am using now!
$db->command(array(
"eval" => new MongoCode("function(){
db['".$toCopy."'].copyTo('".$newName."')
};"
)
));
You can copy a collection on the server with the .copyTo() method for the collection:
db.collection.copyTo("new")
There is no client transfer as there is currently being done by iterating.
If for some reason you want this to be a part of your code then there is the "runCommand" option which has a longer syntax. So in PHP code, do the longer version of this with "eval":
$db->command(array(
"eval" => new MongoCode("function(){ " .
"db.collection.find().forEach(function(doc) { " .
"db.newcollection.insert(doc); " .
"}); " .
"};"
);
));
That will run the copy on the server. Take care to read the documentation and warnings on db.eval(). And aside from all else, but much the same as you were doing, then you must re-create all indexes on the target collection that you want to use.
But in general this will be a better way than iterating over a client connection.
Have you tried to sort the cursor like:
$cursor = $collection->find();
$cursor = $cursor->sort(array('name_of_key_variable' => 1)); //sorts in ascending order
foreach($cursor as $doc) {
...
}
You might also try more of the MongoCursor options listed here:
http://www.php.net/manual/en/class.mongocursor.php at the table of contents

Global variables to pull from an associative array/object?

I have 50 dots on a page, each individual divs. When I click one, I want to use the ID to pull values out of an array. I can get the ID but I'm having trouble using that value to get stuff out of my array. Perhaps a global variable problem? Not sure. Not even sure if this is the best way to handle multiple clicks that access multiple data. Any help is appreciated!
var location0 = {"name" : "Location 1", "image" : "image1.jpg"};
$('.dot').click(function(){
var thisLocation = $(this).attr("id");
alert(thisLocation); //Returns "location0"
alert(thisLocation["image"]); //Returns "undefined"
});
Here's a fiddle.
I'd do it like this :
var locations = {
location1 : {"name" : "Location 1", "image" : "image1.jpg"},
location2 : {"name" : "Location 2", "image" : "image2.jpg"}
}
$('.dot').click(function(){
alert(locations[this.id].name);
});
​
FIDDLE
$(this).attr("id") returns a String "location0". If you want to use it you have to get an actual location0 variable, so you have to replace one of your code lines using eval() function. like this:
var thisLocation = eval($(this).attr("id"));
I would however recommend using a new array, where "location0" would be a key, then you would just need to access a key with a string like locations["location0"] and avoid using eval().
you need to access it like this:
var test = {
location0: {"name" : "Location 1", "image" : "image1.jpg"}
};
$('.dot').click(function(){
var thisLocation = $(this).attr("id");
alert(thisLocation); //Returns "location0"
alert(test[thisLocation]["image"]); //Returns "undefined"
});
​
edit: this works
Also the reason why it doesn't work for you at first place is because thisLocation is a string, not an object it self, so you need to use brackets to access objects property by passing name. I just wouldn't advice

How to read JSON(server response) in Javascript?

I am sending some request on a server and it's reply me this:
{"COLUMNS":["REGISTRATION_DT","USERNAME","PASSWORD","FNAME","LNAME","EMAIL","MOBILE","FACEBOOK_ID"],"DATA":[["March, 17 2012 16:18:00","someuser",somepass,"somename","somesur","someemail",sometel,"someid"]]}
I tried a lot but nothing seems to working for me!
var xml2 = this.responseData;
var xml3 = xml2.getElementsByTagName("data");
Ti.API.log(xml3.FNAME);
For this code I get "null".
Any help would be appreciated!
If you're trying to use JSON format, your problem is that the data within the [...] also needs to be in pairs, and grouped in {...} like here.
For instance,
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
So you might have:
{"COLUMNS": [
{"REGISTRATION_DT" : "19901212", "USERNAME" : "kudos", "PASSWORD" : "tx91!#1", ... },
{"REGISTRATION_DT" : "19940709", "USERNAME" : "jenny", "PASSWORD" : "fxuf#2", ... },
{"REGISTRATION_DT" : "20070110", "USERNAME" : "benji12", "PASSWORD" : "rabbit19", ... }
]
}
If the server is sending you something which you refer to as res, you can just do this to parse it in your Javascript:
var o=JSON.parse(res);
You can then cycle through each instance within columns like follows:
for (var i=0;i<o.COLUMNS.length;i++)
{
var date = o.COLUMNS[i].REGISTRATION_DT; ....
}
see that link. READ JSON RESPONSE
It's perfect.
JSON objects work just like any normal javascript objects or dictionaries
// You can do it this way
var data = this.responseData["DATA"]
// Or this way
var data = this.responseData.DATA
In your case, COLUMNS and data are both arrays, so it looks like you're trying to get the element from data that corresponds to the "FNAME" element in COLUMNS?
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
for(var i=0; i<columns.length; i++){
if(columns[i] == "FNAME"){
Ti.API.log(data[i]);
}
}
EDIT: If you can't change the data on the server end, you can make your own object client side. This also helps if you have to refer to multiple columns (which you probably do).
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
var realData = {};
for(var i=0; i<columns.length; i++){
realData[columns[i]] = data[i];
}
// Now you can access properties directly by name.
Ti.API.log(data.FNAME);
More edit:
My answers only consider the first row in DATA, because I misread originally. I'll leave it up to you to figure out how to process the others.
If you got here trying to find out how to read from [Response object] (as I did) -
this what can help:
- if you use fetch don't forget about res.json() before logging in console
fetch(`http://localhost:3000/data/${hour}`, {
method: 'get'
})
.then(res => {
return res.json()
})
.then((response) => {
console.log('res: ' + JSON.stringify(response))
})
Testing out your code in http://jsonlint.com/, it says that your server's response is not a valid JSON string.
Additionally, I recommend checking out jQuery.parseJSON http://api.jquery.com/jQuery.parseJSON/
Just use JSON.parse(serverResponse)

Categories

Resources