How can I merge individual object values? - javascript

I have the following problem:
I want to read out my table names from a SQL database and then make a comparison as to whether it already exists. I know there is the formula IF EXISTS ... but IF doesn't work .. So here's my previous variant:
First i extracted everything before the filename.csv (C:\Users\Frederic\Desktop\Drag&Drop...) and then the ".csv". Do not be surprised why 51;) The filename is so long
var filename = filePath.slice(51);
var richtigername = filename.replace(".csv","").toString();
console.log(richtigername)
here the result in the console:
for example: fxbewertung
As a second step I let me show the file names:
connection.query('Show tables from datein', function(err, datein) {
let string = JSON.stringify(datein);
let json = JSON.parse(string);
console.log(json)
here the result in the console:
[ { Tables_in_datein: 'fxbewertung' },
{ Tables_in_datein: 'kontoauszug' },
{ Tables_in_datein: 'lsreport' } ]
Furthermore, I extracted the values (name of the SQL tables):
for (var k = 0; k < json.length; k++) {
var werte = Object.values(json[k])
console.log(werte)
};
here the result in the console:
[ 'fxbewertung' ]
[ 'kontoauszug' ]
[ 'lsreport' ]
Now I don't know how i can take the comparison that for example for the file fxbewertung exist a database ('fxbewertung').
My consideration is to somehow browse the individual arrays .. or merge and then browse. At the end should come out true or false
P.S .: it may well be complicated yet but I'm not a real programmer or something;)
Best regards
Frederic

You can use some() method to check if a table exists for that filename.
var tableExists = tables.some(item => item['Tables_in_datein'] === filename);
Live Example:
var tables = [{
Tables_in_datein: 'fxbewertung'
},
{
Tables_in_datein: 'kontoauszug'
},
{
Tables_in_datein: 'lsreport'
}
];
var filename = 'fxbewertung';
var tableExists = tables.some(item => item['Tables_in_datein'] === filename);
if (!tableExists) {
// Table not found for filename.
} else {
// Table found. Do something.
}

Assuming you finished executing your query and stored the data as following:
const queryResult = [ { Tables_in_datein: 'fxbewertung' },
{ Tables_in_datein: 'kontoauszug' },
{ Tables_in_datein: 'lsreport' } ]
You'll then need to map this array to extract the values and store them in a single array like so:
const values = queryResult.map(e=>e[Object.keys(e)[0]]) // ["fxbewertung", "kontoauszug", "lsreport"]
Since you're looking for a true/false result by giving a file name, you'll need to use indexOf to achieve that.
const valueExists = filename => values.indexOf(filename) !== -1
After that execute valueExists with the file name you're looking for:
valueExists("kontoauszug"); // true
valueExists("potato"); // false
Hope this helps!

An efficient solution could be to use Array.prototype.find(). Where it would return from the moment it finds a truthy value and would not iterate till the end (unless the match exists at the end).
Demo Code:
const tablesArr = [
{
Tables_in_datein: "fxbewertung"
},
{
Tables_in_datein: "kontoauszug"
},
{
Tables_in_datein: "lsreport"
}
];
const tabletoFind = "fxbewertung";
const tableFound = tablesArr.find(item => item["Tables_in_datein"] === tabletoFind) ? true: false;
console.log(tableFound);
if(tableFound){
//*yes table found*/
}else{
///*nope table not found*/
}

Related

Updating Json Value with that of another Json

I want to update automatically the value of comments_list with the values in the comments JSON object
const tweet = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]})
const comments = JSON.stringify({"tweet_id":1,"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"})
The final output should look like this
{"tweet_id":1,"created_at":"2022-06-28","comments_list":[{"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"}]}
I'd work with those strings in an object form, otherwise string-manipulation could be slow in some cases.
This is by no means the fastest solution but perhaps the idea behind it can be helpful.
const tweet = [{
"tweet_id": 1,
"created_at": "2022-06-28",
"comments_list": []
}]; // There could be many tweet objects so wrap it in an array
const comments = [{
"tweet_id": 1,
"commenter_id": 2,
"commenter_first_name": "tito",
"commenter_username": "tito_lulu"
},
{
"tweet_id": 1,
"commenter_id": 5,
"commenter_first_name": "me-too",
"commenter_username": "me294"
}
]; // Same here, could be many comments right?
let UpdatedTweets = [];
// There are faster ways to do this, but for your question
tweet.forEach((tweet, tweetIndex) => {
// Loop each tweet
let post = tweet;
comments.forEach((comment, commentIndex) => {
if (comment.tweet_id == tweet.tweet_id) {
// we have a match lets combine them
tweet.comments_list.push({
commenter_id: comment.comment_id,
commenter_first_name: comment.commenter_first_name,
commenter_username: comment.commenter_username
});
}
});
UpdatedTweets.push(post);
});
console.log(JSON.stringify(UpdatedTweets));
The general idea is:
Parse the JSON into JS objects
Update the target object with the complementary information
Stringify the target object into JSON (only if you need to, eg. send the data to some other machine)
In your case:
const tweet = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]});
const comments = JSON.stringify({"tweet_id":1,"commenter_id": 2,
"commenter_first_name":"tito","commenter_username":"tito_lulu"});
let o_tweet = JSON.parse(tweet)
, o_comments = JSON.parse(comments)
;
if (Array.isArray(comments)) { // Test whether that is a single or multiple comments
comments.forEach( c => { o_tweet.comments_list.push(c); });
} else {
o_tweet.comments_list.push(o_comments);
}
console.log(o_tweet);
// Only if needed:
// let newtweet = JSON.stringify(o_tweet)

loop through nested array and return item containing string from the first looped array

I have a nested array with data of file paths. What I was trying to do was get every item in the nested array and first check if the user inputted file name exists in the nested array and if it is found I wanted to log the whole path of that file name.
Currently, I have accomplished the first part but I can't figure out how to get the file path from the file name safely. Basically what I want is after the file name is verified by checking the nested array I want to log the file path which is the whole item in the nested array with that file name. How can I accomplish this?
One thing I have thought of is after verifying the file name run a loop of the nested array and compare every item by splitting it and checking if filename is found in that path. But is this method efficient for large arrays?
Plus note that the numbers in the path are dynamic so multiple items with the same file name but different identification numbers might occur.
c = [
[
['dd\\32323232323:this1', 'dd\\43564564:this2'],
['dd\\5464656646:this3', 'dd\\43543453:this2']
]
]
var currentFileNames = []
var mainDataArrayFilenames = c.forEach((entrys) => {
entrys.forEach((entry) => {
entry.map(function(entry) {
currentFileNames.push(entry.slice(entry.indexOf(':') + 1))
});
})
})
function test() {
const input = document.getElementById('input').value
if (currentFileNames.includes(input) == true) {
//expected full path of file name which is input
console.log("path")
} else {
console.log("name not found")
}
}
<input id="input">
<button onclick="test()">click</button>
Array.prototype.forEach won't return anything. You have to make use of Array.prototype.map if you want to store your result in a variable.
You can also flatten the Array using Array.prototype.flat.
c = [
[
['dd\\32323232323:this1', 'dd\\43564564:this2'],
['dd\\5464656646:this3', 'dd\\43543453:this2']
]
]
var mainDataArray = c
.flat(2) // flatten the array with depth of 3
.map(itm => {
try { // split each entry by :
return itm.split(':');
} catch(e) {
console.error(e);
return []
}
})
.filter(arr => arr.length); // filter all which have no valid information
// this is just for debug purpose and can be removed
mainDataArray.forEach(([path, filename]) => {
console.log(`path "${path}" / filename "${filename}"`)
});
Using the above part, you can search inside the parsed array using Array.prototype.filter and assign the result to a list.
function test() {
const input = document.getElementById('input').value,
list = mainDataArray.filter(([path, filename]) => filename == input);
if (list.length) {
// show all results
console.log(list.map(itm => itm.join(':')).join("\n"));
} else {
console.log("name not found");
}
}
c = [
[
['dd\\32323232323:this1', 'dd\\43564564:this2'],
['dd\\5464656646:this3', 'dd\\43543453:this2']
]
]
var mainDataArray = c
.flat(2) // flatten the array with depth of 3
.map(itm => {
try { // split each entry by :
return itm.split(':');
} catch(e) {
console.error(e);
return []
}
})
.filter(arr => arr.length); // filter all which have no valid information
// this is just for debug purpose and can be removed
mainDataArray.forEach(([path, filename]) => {
console.log(`path "${path}" / filename "${filename}"`)
});
function test() {
const input = document.getElementById('input').value,
list = mainDataArray.filter(([path, filename]) => filename == input);
if (list.length) {
// show all results
console.log(list.map(itm => itm.join(':')).join("\n"));
} else {
console.log("name not found");
}
}
<input type="text" id="input">
<input type="button" onclick="test()" value="Search">

JavaScript array of huge data (500K record) taking time to search and add

My function is called in loop which returns more than 500k record.
I have to insert that record in a JavaScript array. Before inserting records to array need to check existing array has duplicate records or not. If the record is duplicate then exclude the record.
When array size increases the run time of the function is very high. Please suggest me a way to optimize search.
function AddDataToArray(StdName, currObjectSTD, bufferObject, attributes, bufferSTD) {
var result = false;
var existingObjects = AllDataArray.find(item => {
item.OBJECTID==attributes.OBJECTID
&& item.name == bufferObject.name
&& item.StdName == StdName);
});
if (existingObjects.length == 0) {
var currentObject = {
"ID": 0,
"currObjectSTD": currObjectSTD,
"color": bufferObject.color,
"name": bufferObject.name,
"attributes": attributes,
"StdName": StdName,
"objectID": objectID,
"bufferSTD": bufferSTD,
"shape": null,
"shapeSTD": null
};
AllDataArray.push(currentObject);
result = true;
}
return result;
}
As a speedup workaround I suggest you coming up with some kind of hash map based on your array to avoid continuos looping through array
const dataHashMap = _(AllDataArray)
.keyBy(item => `${item.OBJECTID}-${item.name}-${item.StdName}`)
.mapValues(() => true)
.value();
var existingObjects = dataHashMap[`${attributes.OBJECTID}-${bufferObject.name}-${StdName}`]
or alternative solution
let groupedDataHashMap = {}
AllDataArray.forEach(item => {
_.set(
groupedDataHashMap,
[
item.OBJECTID,
item.name,
item.StdName
],
true
)
})
var existingObjects = _.get(
groupedDataHashMap,
[
attributes.OBJECTID,
bufferObject.name,
StdName
],
false
)
I used lodash methods but if you prefer using native array/object methods you can come up with your own implementation, but the idea is the same
P.S you need to create this hash map once you fetched your array and populate it with new items simultaneously with your array to keep it up-to-date with your array

$in for multiple values

var footballerIdToPassive = "qqqqq";
var footballerlevelToPassive = ["3052002","3052003"];
db.goals.find({ "footballer": footballerIdToPassive, "footballerlevel": { $in: [footballerlevelToPassive]}}))
for that it brings nothing but in goals db shell, when i run count of this, count is 1
{ "footballer": "qqqqq", "footballerlevel": "3052002" }
also for
var footballerlevelToPassive = "3052002";
this, it works. but i cant do for multiple. HOw can i do this work?
i need to use each , i need to update each one
footballerlevelToPassive is already an array, there's no need to wrap it in another array again in your query, just reference it directly with $in as
var footballerIdToPassive = "qqqqq";
var footballerlevelToPassive = ["3052002","3052003"];
db.goals.find({
"footballer": footballerIdToPassive,
"footballerlevel": { "$in": footballerlevelToPassive }
})
which is equivalent to the query
db.goals.find({
"footballer": footballerIdToPassive,
"$or": [
{ "footballerlevel": "3052002" },
{ "footballerlevel": "3052003" }
]
})
Quick demo

Javascript array parsing

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"

Categories

Resources