Need Help to adding new array into JSON object - javascript

I'm making an file managing web page with nodejs and need some help.
I'm adding some informations into JSON object which recieved from DB.
the DB constains stage informations and I should link informations about stage files.
this is code for the function. Added comments into codes.
DBmodel.findOne({'key': 'server'}).exec(function (err, data) {
for (var i = 0; i < data.stage.length; i++) {
// this was successful. I added an array to check each files.
data.stage[i].packFileNameArray = data.stage[i].packFileName.split("/");
data.stage[i].packVersionArray = data.stage[i].packVersion.split("/");
// this is a problem. I will add file information for each file.
// I
for (var j = 0; j < data.stage[i].packFileNameArray.length; j++) {
fs.stat(dirPath + data.stage[i].packFileNameArray[j], function (err, fileStat) {
if (err) {
// this was first try. I thought the array will be automaticallt created.
data.stage[i].isExist[j] = 'NO';
data.stage[i].mTime[j] = '0';
data.stage[i].size[j] = '0';
} else {
// this was second try. I tried push into each time.
data.stage[i].isExist.push('YES');
data.stage[i].mTime.push(fileStat.mTime);
data.stage[i].size.push(fileStat.size);
}
console.log(data.stage[i].isExist[j]);
console.log(data.stage[i].mTime[j]);
console.log(data.stage[i].size[j]);
});
}
}
});
I want to know how I can add additional informations as an array into the JSON object.
Thank you.

data.stage[i].push({ isExist: 'Yes'});
etc

You have to create the arrays (as the do not seem to exist) before you can push data into them:
DBmodel.findOne({'key': 'server'}).exec(function (err, data) {
for (var i = 0; i < data.stage.length; i++) {
// this was successful. I added an array to check each files.
data.stage[i].packFileNameArray = data.stage[i].packFileName.split("/");
data.stage[i].packVersionArray = data.stage[i].packVersion.split("/");
data.stage[i].isExist = [];
data.stage[i].mTime = [];
data.stage[i].size = [];
//...

Related

Array returning empty in Javascript

This is all still pretty new to me but I am running into an interesting behavior issue when generating an array of numbers in a NodeJS application that handles .nessus result files. First, some details on what I am trying to accomplish. My application generates an array [1234,1223,1222] of entries from an uploaded "results" file that is then used to query a mongodb instance to determine if those entries are currently in the DB. If those entries are not currently in the mongodb instance, it redirects to a page where a user can edit them before being added. If there are no new entries, it goes to a page to generate a report on the entries.
When a file is uploaded, it stores the new entries. In .nessus files, sometimes there is more than one host with entries. That changes the json structure and the function needs to iterate a little differently. The following function is how those entries are stored. This is important as this is where the weird behavior originates (I think)
function parsePluginNumbers(json){
var pluginNumbers = []
//Let's check the number of hosts
var hostLength = json['NessusClientData_v2']['Report'].ReportHost.length
if (hostLength != undefined) {
for (var i = 0; i < hostLength; i++) { //Since there is more than 1, need to iterate over each host to find the findings.
var item_length = json['NessusClientData_v2']['Report'].ReportHost[i].ReportItem.length
for (var t = 0; t < item_length; t++) { //Iterate through each finding on each host
if (json['NessusClientData_v2']['Report'].ReportHost[i].ReportItem[t].risk_factor != 'None') {
var newEntry = json['NessusClientData_v2']['Report'].ReportHost[i].ReportItem[t].pluginID
if (pluginNumbers.indexOf(newEntry) == -1) {
pluginNumbers.push(newEntry)
}
else {
continue
}
} else {
continue
}
}
}
} else {
var item_length = json['NessusClientData_v2']['Report']['ReportHost'].ReportItem.length
for (var t = 0; t < item_length; t++) { //Iterate over findings
if (json['NessusClientData_v2']['Report']['ReportHost'].ReportItem[t].risk_factor != 'None') {
var newEntry = json['NessusClientData_v2']['Report']['ReportHost'].ReportItem[t].pluginID
if (pluginNumbers.indexOf(newEntry) == -1) {
pluginNumbers.push(newEntry)
}
else {
continue
}
} else {
continue
}
}
}
return pluginNumbers
}
Once those plugins are stored. Another function is called to look if those results are in the mongodbinstance. In this function, those plugins are in an array "pluginsTotal".
function queryForNewResultsInANessusFile(pluginsTotal, collectionname, filename){ //function to call mongodb query and send results to parseNewFindings and parseOldFindings.
var db = req.db;
var collection = db.get(collectionname);
collection.find({ 'PluginNumber' : { $in: pluginsTotal }}, 'FindingTitle FindingDescription Remediation Mitigation SeeAlso PluginFamily PluginNumber CVE Risk -_id', function(error, result){
var newPluginArray = parseOutFindingNumbersInMongoDB(result, pluginsTotal);
//IF statements go here with specific redirects as needed to check if there are new values not in the repo
}
During this collection.find call, there is a function parseOutFindingNumbersInMongoDB that is called to determine if there are plugins in the .nessus results file that are not in the repo. It compares the results from collection.find and pluginsTotal (generated from the first function) and returns an array of the new plugins that are not in the repo. The function details are below:
function parseOutFindingNumbersInMongoDB(repoResults, reportPlugins) {
for (var i = 0; i < repoResults.length; i++){
var index = reportPlugins.indexOf(repoResults[i].PluginNumber);
if (index != -1) {
reportPlugins.splice(index, 1);
}
else {
continue
}
}
return reportPlugins
}
Now to my question --- When I upload a .nessus file with more than one host, parseOutFindingNumberInMongoDB always returns empty even though there are new entries. What gives? Is it the way I parse out the numbers to begin with in the parsePluginNumbers function or is because it is called in the collection.find synchronous function (This seems unlikely as if there is one host, it returns the new plugin values as I want)? Any thoughts/ideas/review would be much appreciated as I cannot figure out what is wrong. I have checked the data types within the array before being passed into the functions and they all match up.
It's always returning an empty array because every element in the array matches the condition to be spliced.
You first retrieve elements that have a PluginNumber in pluginTotal array with this filter { $in: pluginsTotal }
collection.find({ 'PluginNumber' : { $in: pluginsTotal }}, 'FindingTitle FindingDescription Remediation Mitigation SeeAlso PluginFamily PluginNumber CVE Risk -_id', function(error, result){
var newPluginArray = parseOutFindingNumbersInMongoDB(result, pluginsTotal);
}
Then you remove all elements that have a PluginNumber in pluginTotal
var index = reportPlugins.indexOf(repoResults[i].PluginNumber);
if (index != -1) {
reportPlugins.splice(index, 1);
}
So the result is always an empty array.

How to combine two or multiple JSON objects into one in AngularJS?

Is it possible to add new data in API JSON response in AngularJS? I am consuming a REST API which returns country details, but I want to add more details to it.
After the API call, I'm getting this response:
There are few empty fields (red arrow). I need to fill it up using another API into each respective country, and also add new keys such as "id" etc if possible.
Is it possible to achieve this? and how?
Here is the code:
Api service.js (data which are going to be added)
$http.get("https://api.../getfile/rohit/fw18countries").success(function(data) {
teams = data.teams;
//console.log(data);
/* shuffle(teams); */
});
return {
GetTeams: function(){
return teams;
},
get: function(teamId) {
for (var i = 0; i < teams.length; i++) {
if (teams[i].id === parseInt(teamId)) {
return teams[i];
}
}
return null;
}
}
Controller.js
/* all teams data */
$scope.Allteams = wcAPI.GetTeams();
/* REST API call */
$http.get("http://api.../v1/competitions/467/fixtures")
.then(function(data) {
$scope.country = data;
console.log($scope.country);
});
So now, I need to update $scope.country (REST API data) using $scope.Allteams (my static data) with respective fields as mentioned above. Need to merge them respectively.
You can try this with the following code. Looping through the data arrays and findig the right one. Then adding all values to the object.
for(var i = 0; i< $scope.country.length; i++) {
//Find the right index from $scope.country
for(var j = 0; j< $scope.Allteams.length; j++) {
// TODO here you have to campare by right value
if($scope.country[i].id == $scope.Allteams[j].teamId) {
for(var key in $scope.AllTeams[j]) {
if(!$scope.Allteams[j].hasOwnProperty(key)) continue;
//Adds the value to the object
$scope.country[i][key] = $scope.Allteams[j][key];
}
break;
}
}
}

JavaScript - push results from for loop into array (with SoundCloud API)

I have this function that iterates through a user's favourited track genres on SoundCloud, and then I want to push these results into an array however am having problems. Any suggestions?
SC.connect(function() {
SC.get('/me/favorites', function(favorites) {
console.log(favorites)
for (i = 0; i < favorites.length; i++) {
console.log(favorites[i].genre);
favorites[i].genre.push(meGenrePref);
}
var meGenrePref = [];
console.log(meGenrePref);
});
});
I'm not expert on SoundCloud APIs but watching your code I thought this solution:
var meGenrePref = [];
SC.connect(function(){
SC.get('/me/favorites',function(favorites) {
console.log(favorites);
for(var i = 0; i < favorites.length; i++)
{
console.log(favorites[i].genre);
meGenrePref.push(favorites[i].genre);
}
console.log(meGenrePref);
});
});
You were trying to push the contents to a wrong variable, which was the response from the API.
In this solution we are saving to meGenrePref all genres.

Concatenate argument to update a certain array with Angular/JS

I'd like to pass in a string from one of my functions that will let another function know which array to update within another array. All the attempts I've tried end in poor errors that really don't lead me anywhere productive so far.
function likeFeedItem(itemId, feedItemIndex) {
postActionsService.likeFeedItem(itemId)
.then(function success(response) {
var resource = 'capabilities.chatterLikes';
ctrl.testUpdate(response.data, feedItemIndex, resource);
})
.catch(ctrl.showError)
};
function testUpdate(feedItemData, feedItemIndex, resource) {
ctrl.feedResult.elements[feedItemIndex] . resource = feedItemData.resource;
// Output should work/look like this would
ctrl.feedResult.elements[feedItemIndex].capabilities.chatterLikes = feedItemData.capabilities.chatterLikes
}
Change:
ctrl.feedResult.elements[feedItemIndex] . resource = feedItemData.resource;
To:
resource = resource.split('.');
ctrl.feedResult.elements[feedItemIndex][resource[0]][resource[1]] = feedItemData[resource[0]][resource[1]];
EDIT: Also removed AngularJS tag as this doesn't have anything to do with it specifically.
EDIT2:
If you have an unknown amount of keys, you can loop like so:
resource = resource.split('.');
var current_node = ctrl.feedResult.elements[feedItemIndex];
for (var i = 0, n = resource.length; i < n; i++) {
current_node = current_node[resource[i]];
}

HTML rendering before for-loop finishes executing, only first item in for-loop showing

I am trying to render an html page that contains all of the posts that a user has received. Right now the issue I am having (shown under Way 1) is that when I call the function renderPosts after the web socket is received, only the first post in the array is rendered (the array has more than one post in it).
On the other hand, Way 2 in which I have no for loop and instead manually render each post works in that all four posts are rendered. But I need to be able to work with an arbitrary number of posts which is why I need to use the for loop.
I am using socket.io and javascript.
Way 1:
socket.on('postsToRender', function(arrayOfPostsToRender) {
renderPosts(arrayOfPostsToRender);
});
function renderPosts(arrayOfPostsToRender) {
for (var index = 0; index < arrayOfPostsToRender.length; index++) {
renderPost(arrayOfPostsToRender[index]);
}
}
function renderPost(postToRender) {
var feed = document.getElementById("feed");
var postContent = document.createTextNode(postToRender.content);
var post = document.createElement("div");
post.appendChild(postContent);
feed.appendChild(post);
}
Way 2:
socket.on('postsToRender', function(arrayOfPostsToRender) {
renderPost(arrayOfPostsToRender[0]);
renderPost(arrayOfPostsToRender[1]);
renderPost(arrayOfPostsToRender[2]);
renderPost(arrayOfPostsToRender[3]);
});
function renderPost(postToRender) {
var feed = document.getElementById("feed");
var postContent = document.createTextNode(postToRender.content);
var post = document.createElement("div");
post.appendChild(postContent);
feed.appendChild(post);
}
Try this:
function renderPosts(arrayOfPostsToRender) {
for (var index = 0; index < arrayOfPostsToRender.length; index++) {
(function(i){
renderPost(arrayOfPostsToRender[i]);
})(index);
}
}

Categories

Resources