getting last element in JSON not working - javascript

I am trying to take the last element in a JSON. I know order is not preserved, but the keys are unix timestamps so I can just sort. I am working from this question:
get last element of a json object in javascript
But I get nothing logged to the console and no errors.
my code:
var mydata = {"1509937402379":"7348.01","1509937412486":"7348.01","1509937422253":"7348.01","1509937426286":"7348.01","1509937430066":"7345.54"}
console.log(mydata[Object.keys(obj).sort().pop()]);
https://jsfiddle.net/Lmb5sd1m/1/

You missed.. .You require to use Object.keys(mydata).
var mydata = {"1509937402379":"7348.01","1509937412486":"7348.01","1509937422253":"7348.01","1509937426286":"7348.01","1509937430066":"7345.54"}
Review same fiddle https://jsfiddle.net/Lmb5sd1m/1/

Related

Return Array of Data using Google Assistant from Firebase

The structure I have for my firebase database is like this:
fruits:
apple,5
banana,6
I want to put apple and banana in an array so that when i give a command to Google Assistant, it would give me apple, 5 and banana, 6. The code I have is like the one below:
function handleCommand(agent) {
return admin.database().ref('Fruits').child().once("value").then((snapshot) =>{
var i;
var fruitlist=[];
//puts each snapshot child of 'Fruit' in an array
snapshot.forEach(function(item) {
var itemVal = item.val();
fruitlist.push(itemVal);
});
//outputs command in google assistant
for (i=0; i < fruitlist.length; i++) {
agent.add(fruitlist[i]);
}
})
The default response is "not available".
I get the following in the execution logs:
Firebase.child failed. Was called 0 aruguments. expects at least 1.
I do not know which argument to put inside the Firebase.child. if i want all fruits to be "spoken" by Google Assistant. Below is a picture of my firebase structure.
The error looks like the one below:
What I am currently doing now to just output the fruits are manually entering each child in the code like this and removed the ".child" in the return statement:
Which gives me the output below which is also what I want to see but using arrays as the solution I am using now is very much hardcoded:
As the error message suggests, and as you surmise, the child() call expects a parameter - in particular, the name of the child node you want to get information from. However, since you want all the children of the "Fruits" node - you don't need to specify it at all. The child() call just navigates down through the hierarchy, but you don't need to navigate at all if you don't want to.
The snapshot you get back will have a value of the entire object. In some cases, this can be pretty large, so it isn't a good idea to get it all at once. In your case, it is fairly small, so not as big a deal.
On the JavaScript side, you can now handle that value as an object with attributes and values. Your original code didn't quite do what you said you want it to, however - you're getting the value, but ignoring the name (which is the attribute name or key). You can iterate over the attributes of an object in a number of ways, but I like getting the keys of the object, looping over this, getting the value associated with the key, and then "doing something" with it.
While I haven't tested the code, it might look something like this:
function handleCommand(agent) {
return admin.database().ref('Fruits').once("value").then((snapshot) =>{
// Get an object with all the fruits and values
var fruits = snapshot.val();
// Get the keys for the attributes of this object as an array
var keys = Object.keys( fruits );
// Iterate over the keys, get the associated value, and do something with it
for( var i=0; i<keys.length; i++ ){
var key = keys[i];
var val = fruits[key];
agent.add( `The number of ${key} you have are: ${val}` );
}
})
While this is (or should be) working Firebase and JavaScript, there are a couple of problems with this on the Actions on Google side.
First, the message returned might have some grammar problems, so using your example, you may see a message such as "The number of Apple you have are: 1". There are ways to resolve this, but keep in mind my sample code is just a starter sample.
More significantly, however, the call to agent.add() with a string creates a "SimpleResponse". You're only allowed two simple responses per reply in an Action. So while this will work for your example, it will have problems if you have more fruit. You can solve this by concatenating the strings together so you're only calling agent.add() once.
Finally, you may wish to actually look at some of the other response options for different surfaces. So while you might read out this list on a speaker, you may read a shorter list on a device with a screen and show a table with the information. Details about these might be better addressed as a new StackOverflow question, however.

JavaScript + MySQL: use fields as parameter in result

I'm quite new to JavaScript and I have the following issue:
I have a Node.JS server on which a webclient can connect and execute functions. One function is to look into a MySQL database and gather information.
The query is done right and I obtain the correct raw information as for example:
Here is my code:
So I correctly get the column names using the fields (fields[0].name = Count_0)variable and I am able to get the correct value using the result (result[0].Count_0 = Gray).
However, I am unable to merge the two lines in order to create the list of colors using something like this in a loop: result[0].fields[0].name = Gray
Is there an easier way to do this or not ?
Thanks,
Nicola.
In Javascript, you can use the [] operator to access a variably-named property in an object.
Instead of using result[0].fields[0].name, use
result[0][fields[0].name]
You won't get any runtime errors for accessing a property that doesn't exist, so you'll want to check whether that value is undefined before using it somewhere else.
It seems you want to get the color. If so, you can get the color by this
let color = result[0][fields[0].name];
The idea is use fields[0].name as key of result[0].
This is the breakdown of above single line.
let key = fields[0].name;
let color = result[0][key];

Append JSON to another JSON

I have two JSON objects which are Youtube API responses.
I want to append some part of the second JSON (source) to a particular position in the first JSON (destination) and finally have one merged JSON to send to view.
I've tried like so:
var merged = Object.keys(source).forEach(function(key) {
destination.items[key].contentDetails = source[key].items[key].contentDetails;
})
They both contain same number of item sets so I use the same index key for destination within the loop of source and append each to the destination JSON.
destination.items[key].contentDetails is a valid reference that returns correct value in the console but when inside this loop it's undefined.
What am I doing wrong here?
I'm not quite sure about this practice for such task so I'd greatly appreciate for some direction.

working with PHP array in javascript

building a countdown to a date that is based on a variable integer that will indicate how many days are left. Im trying to return the result as the difference in unix time between the current time and the future time in an array including days, hours, minutes, seconds. All seems to work fine however instead of an array it seems to return the results as a string.
Can anyone see what is wrong with my markup here? Or do i need to do another conversion within javascript?
PHP
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo json_encode($zTimeCombined);
How im accessing the "array" in JS (within a GET success function)
var zDays = results[0];
var zHours = results[1];
var zMinutes = results[2];
var zSeconds = results[3];
edit:
possible duplicate of this question (use php array in javascript?), however the answers were not as succinct and were not as simple as was needed here. Id say this question is really very basic but will be handy for non PHP users like myself
The response you're getting from the AJAX is in string format, not in JSON.
To convert it to json format use JSON.parse()
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.
var result = JSON.parse(response);

LocalStorage with an object array

When storing an array in local storage, then retrieving the results like this works fine
myarray = ["cat", "dog", 1];
localStorage["storedArray"] = JSON.stringify(myarray);
JSON.parse(localStorage["storedArray"]);
But when i try to store an object array full of Google maps LatLng information all that is printed is [object][object], [object][object] and so on.
localStorage["positions"] = JSON.stringify(this.positions);
JSON.parse(localStorage["positions"]);
Same code just changing the array stored, I know the information in it is fine since Im using it to print lines on the map.
Have you tried the following?
localStorage["positions"] = JSON.stringify(this.positions[0]);
JSON.parse(localStorage["positions"]);
You could try using a console.log to display the [object]. If it has indexes you will need to reference the index as I mentioned in the above example. Open your browser console and see what is the output, and change your code accordingly.
console.log(this.positions);
Hope this helps in some way. Hope you find the answer and share it.

Categories