How to access RowDataPacket mysql-node.js - javascript

connection.query('
SET #update_id := 0;
UPDATE relations set x1 = ?, y1 = ?, id = (SELECT #update_id := id) WHERE element_to =?;
SELECT #update_id;',[data.x2,data.y2,id],function(err,result){
if(err){console.error(err);}
else{console.log(result);console.log(result.#update_id);}
});
I am getting the following result from a query execution:
[ RowDataPacket {
'#update_id': 'WAbWA1WA5WA2WA8WAdWA4WA9' } ] ]
How do I access the #update_id field to store the value in a variable. I know these are objects and I tried the following to access them such as follows:
results.#update_id;
But I get undefined when I try to log the value. How to get the value?

Try this:
results[0].#update_id

use console.log(JSON.stringify(result));
then if you want to get access data on variable
var data = JSON.stringify(result[0].#update_id)
console.log(data);
you can't use index on var E.G
console.log(data[0].#update_id) it is wrong

just conver the result to array, then you can easily access the data, i get solved by doing this
let res = JSON.parse(JSON.stringify(result));

Related

How can I get a specific element value of object in localstorage

I'm trying to get "city" value (in case: Porto, Lisboa, Leiria, Londres) of localstorage and put It in a variable. I wish to do this in a loop for and use each city name in a function.
Now, I'm here:
Object.entries(localStorage).map(([id, valueJSON]) => {
cityName = JSON.parse(JSON.stringify(localStorage.getItem('persist:root', 'allWeather', 'city')));
console.log(cityName)
My return is this:
{"allWeather":"[{"id":0.47266066302275545,"city":"Porto"},{"id":0.8669553925029849,"city":"Lisboa"},{"id":0.5502373167192611,"city":"Leiria"},{"id":0.19655712000371484,"city":"Londres"}]","_persist":"{"version":-1,"rehydrated":true}"}
How can I do this? I appreciate any help.
Try this:
const cities =
// Parse the localstorage item to object
JSON.parse(localStorage.getItem('persist:root', 'allWeather', 'city'))
// Get the allWeather property
.allWeather
// Get the city properties only
.map(weather => weather.city);
You need to convert the object string to JSON using JSON.parse
[{ city }] this part is not right. Change it to city

Javascript ForEach on Array of Arrays

I am looping through a collection of blog posts to firstly push the username and ID of the blog author to a new array of arrays, and then secondly, count the number of blogs from each author. The code below achieves this; however, in the new array, the username and author ID are no longer separate items in the array, but seem to be concatenated into a single string. I need to retain them as separate items as I need to use both separately; how can I amend the result to achieve this?
var countAuthors = [];
blogAuthors = await Blog.find().populate('authors');
blogAuthors.forEach(function(blogAuthor){
countAuthors.push([blogAuthor.author.username, blogAuthor.author.id]);
})
console.log(countAuthors);
// Outputs as separate array items, as expected:
// [ 'author1', 5d7eed028c298b424b3fb5f1 ],
// [ 'author2', 5dd8aa254d74b30017dbfdd3 ],
var result = {};
countAuthors.forEach(function(x) {
result[x] = (result[x] || 0) + 1;
});
console.log(result);
// Username and author ID become a single string and cannot be accessed as separate array items
// 'author1,5d7eed028c298b424b3fb5f1': 15,
// 'author2,5dd8aa254d74b30017dbfdd3': 2,
Update:
Maybe I can explain a bit further WHY on what to do this. What I am aiming for is a table which displays the blog author's name alongside the number of blogs they have written. However, I also want the author name to link to their profile page, which requires the blogAuthor.author.id to do so. Hence, I need to still be able to access the author username and ID separately after executing the count. Thanks
You could use String.split().
For example:
let result = 'author1,5d7eed028c298b424b3fb5f1'.split(',')
would set result to:
['author1' , '5d7eed028c298b424b3fb5f1']
You can then access them individually like:
result[1] //'5d7eed028c298b424b3fb5f1'
Your issue is that you weren't splitting the x up in the foreach callback, and so the whole array was being converted to a string and being used as the key when inserting into the results object.
You can use array destructuring to split the author name and blog id, and use them to optionally adding a new entry to the result object, and then update that result.
countAuthors = [
['author1', 'bookId1'],
['author2', 'bookId2'],
['author1', 'bookId3'],
['author1', 'bookId4'],
['author2', 'bookId5']
]
var result = {};
countAuthors.forEach(([author, id]) => {
if (result[author] === undefined) {
result[author] = {count: 0, blogIds: []};
}
result[author].count += 1;
result[author].blogIds.push(id);
});
console.log(result);

How to split string from number of / in node.js?

My sting is like this
console.log(fields.urlOfFolder); // console is [ '122/122/47/49/50' ]
and i want only first 122 how it is possible ?
i tried this code..
var customerid = fields.urlOfFolder.split('/')[0];
console.log(customerid);
but it gives error like this TypeError: fields.urlOfFolder.split is not a function
fields.urlOfFolder is an array. To access the first value from array, use fields.urlOfFolder[0]
var fields = {
urlOfFolder : [ '122/122/47/49/50' ]
};
var customerid = fields.urlOfFolder[0].split('/')[0];
console.log(customerid);
fields.urlOfFolder is an array with one entry, you need to pull the string out first:
var customerid = fields.urlOfFolder[0].split('/')[0];

fetch data from nested JSON object in a single line

This is my JSON data ....
{"comp1":["$.Create_Keypair1_Keypair_name"]}
I want to get the value "Create_Keypair1_Keypair_name".but all the keys and values are dynamic.but the object always have single data.
I have Object.keys(temp).It shows only ["comp1"] i need
$.Create_Keypair1_Keypair_name only....
Try this:
var data = {"comp1":["$.Create_Keypair1_Keypair_name"]}
for (var key in data) {
console.log(data[key])
}
This will log $.Create_Keypair1_Keypair_name.
From what I am understanding each object will have a single value. If the is the case then you do not need the array in the object. You can do this.
var tempy = {"comp":"ksmdfnsfdnsdfn"}
Then do this to ge the value.
tempy.comp
Or if you need the keys.
Object.keys(tempy)
you might be looking for this
var temp = {"comp1":["$.Create_Keypair1_Keypair_name"]}
Object.keys(temp).forEach(function(key){
console.log(temp[key]);
});

extract single variable from JSON array

I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array

Categories

Resources