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];
Related
I've got an array of employee's and assigned to each employee are a few elements.
Sample of array below:
var employees = [
{"name":"Johhny Test","salary":"1","email":"abc#123.com"},
{"name":"Mike Milbury","salary":"10","email":"184895#hdsjhfs.com"}
];
I've got a means of gathering the employee's last name and I'm storing it in a variable. I'd like to be able to search for the indexOf the last name housed in this variable so that I know at which position within the array that match is made.
So for instance, this array could be 100 items in size. Ideally I want to know that someone with the last name of "johnson" is in position 50 of this array. That way, I can go in and get the salary and email associated with their record from position 50 in the array.
The code I've got so far is this:
var lname = "Test";
var lnameMatch = employees.indexOf(lname);
console.log(lnameMatch);
This isn't working though - my console is logging -1, suggesting that it doesn't exist in the array. Is there a way that I can specify a element of that array to search against?
Almost like employees(name).indexOf(lname) where it is searching against the name element?
Or am I going about this all wrong and there is perhaps an easier less messy way to accomplish this?
You can use .findIndex:
const employees = [
{"name":"Johhny Test","salary":"1","email":"abc#123.com"},
{"name":"Mike Milbury","salary":"10","email":"184895#hdsjhfs.com"}
];
const lastName = "Test";
const index = employees.findIndex(employee => {
const { name = '' } = employee;
const nameParts = name.split(' ');
const lname = nameParts[nameParts.length-1];
return lastName === lname;
});
console.log(index);
console.log(employees[index]);
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);
My array payload is like: msg.payload[index].temp. I cut the array in single parts to publish the single parts of the array via MQTT.
So I got msg.payload.temp and msg.parts.index.
msg:{
payload:{
address: "e4:32:a3:3a:99:97";
temp: "32"
}
parts: {
type: "array";
index: "16";
count: "17";
}
}
Is it possible to put the number of the index into the name msg.payload.temp? So I got something like msg.payload.temp_6. I tried to combine strings together like:
var temp = "msg.payload.temp_" + msg.parts.index.toString();
temp = payload.temp;
return msg;
Do I need a conversation from string to json so Node-Red detect the property?
You can add a property to msg.payload.
let index = 6;
msg.payload["temp"+index] = 'Whatever';
This will be available as
console.log(msg.payload.temp6); // Whatever
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));
var usersRows = [];
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
rows.forEach(function(row) {
usersRows.push(row);
});
console.log(usersRows);
}
else {
console.log('Error while performing Query.' + err);
}
});
It returned to me:
var usersRows = [ [ RowDataPacket { id: 1, name: 'sall brwon', number: '+99999999\r\n' } ] ];
I need to parse this and remove rowdatapacket; I need result like this:
userRows = { id: 1, name: 'my name is', number: '+999999\r\n' };
If you need to get rid of RowDataPacket's array and save it in yours you can also use this:
usersRows = JSON.parse(JSON.stringify(results));
Have you tried
userRows = RowDataPacket;
You might want to try JSON.stringify(rows)
Was unable to understand and implement the accepted the answer.
Hence, tried the long way out according the results I was getting.
Am using "mysql": "2.13.0" and saw that the this library returned array of array out of which:
Index 0 had array of RowDataPackets
Index 1 had other mysql related information.
Please find the code below:
var userDataList = [];
//Get only the rowdatapackets array which is at position 0
var usersRows = data[0];
//Loop around the data and parse as required
for (var i = 0; i < usersRows.length; i++) {
var userData = {};
//Parse the data if required else just
userData.name = userRows.firstName + userRows.lastName;
userDataList.push(userData);
}
If no parsing is required and you just want the data as is, you could use the solution like mentioned in link How do I loop through or enumerate a JavaScript object?
Have not tried it but could be tweaked and worked out.
There should be simpler way to do it but as a novice I found the above way server the purpose. Do comment in case of better solution.
RowDataPacket is the class name of the object that contains the fields.
The console.log() result [ [ RowDataPacket { id: 1, name: 'sall brwon', number: '+99999999\r\n' } ] ] should be read as "an array of one item, containing and array of one item, containing an object of class RowDataPacket with fields id, name, and number"