I have a test that provides 4 values:
fPortTotal = a number with how many ports in a firewall test.
fProtocol = an array with what protocol the port is (ex. UDP, TCP)
fPorts = an array with what port number
fStatus = an array with open or closed depending on the port
in all the arrays [0] is the first port, [1] is the 2nd, and so on.
I want to use the .map method to display each port's information in a <p>. The issue is I'm having a large amount of difficulty understanding the .map method and how to use it. I beleave the "skeleton" of the function should look like this:
function populateFw(fPorts, fStatus, fPortTotal, fProtocol) {
var output = document.getElementById('firewallRes');
var text = document.createElement ('p');
text.id = 'firewallEndResults';
text.innerHTML = arrayOfArrays.map;
}
any help would be appreciated.
You can try something like this:
function populateFw(fPorts, fStatus, fPortTotal, fProtocol) {
var output = document.getElementById('firewallRes');
fPorts.forEach((port, index) => {
const text = document.createElement('p');
text.innerText= `${port}: ${fProtocol[index]} - ${fStatus[index]}`;
output.appendChild(text);
})
}
ForEach would be better here. Map returns an object, you don't need that.
fStatus.forEach((_, index)=>{
//then using index acces all the information
const protocol = fProtocol[index];
const protNumber = fPorts[index]
....
text.innerHTML += 'Protocol is '+protocol+' and port number is '+protNumber;
});
Edit: also example of Talmacel Marian Silviu is basically the same thing.
do it like this:
for(i=0; i<fPorts; i++){
var text = document.createElement ('p');
text.id = `firewallEndResults${i}`;
text.innerHTML = `${fStatus[i]}, ${fPortTotal[i]}, ${fProtocol[i]}`;
somediv.appendChild(text); // don't forget
}
map is function for change array items and need callback
const newArray = arrayOfArrays.map(callback)
or
const newArray = arrayOfArrays.map((i)=>{ do something in cycle })
if you use React you can use map in JSX, but this is other story
Related
I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.
let correctAnswer = document.getElementById("correct-answers");
document.querySelector(".check").onclick = function () {
/* Hide unneeded sections and showing scores */
quiz.classList.add("hidden");
correctAnswer.classList.remove("hidden");
/*Showing all previous scores */
const lastScore = localStorage.getItem("latestScore") || [];
const scoreDetail = lastScore.split(',');
scoreDetail.push(score);
localStorage.setItem("latestScore", scoreDetail);
let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;
scoreDetail.map((items, index) => {
userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`
});
let userScoreBoard = document.getElementById("user-score");
userScoreBoard.innerHTML = userScoreTemplate;
localStorage.getItem() will return a string.
You need adjust your code accordingly to default to a string in case the item is not defined:
const lastScore = localStorage.getItem("latestScore") || "";
In your code lastScore is an array, not a string, so the split method will not work on it. It works only on strings.You can use JSON.Parse like that. This will convert array data into javascript array.
const scoreDetail = JSON.parse(lastScore) || [];
scoreDetail.push(score);
And after that convert the array into a JSON string :
localStorage.setItem("latestScore", JSON.stringify(scoreDetail));
is latest score is a obj/array/string or what?
If it's an array/object then wrap localStorage.getItem in JSON.parse() so js can convert array data into js array
As per the error, You are trying to apply split on an array instead of a string.
Looks like, localStorage.getItem("latestScore") is undefined while you are trying to access it and it assigned an empty array to lastScore variable.
Hence, Instead of
const lastScore = localStorage.getItem("latestScore") || [];
Use
const lastScore = localStorage.getItem("latestScore") || "";
I have a CSR and I can parse all the data with pkijs.org lib, but I have no luck to parse alternative names data. How is it possible to do with a javascript? Some other libs can be in use, I guess, do you know one?
Following the docs of CertificationRequest class provided by pkijs here https://pkijs.org/docs/classes/CertificationRequest.html. We can see that the structure of a CSR. The subject alternative name will be stored in attributes propery of CertificationRequest object. But the structure inside of attributes is quite complex to make it as plain text. This is my code used to print out the subject alternative name
const pkijs = require('pkijs');
const utils = require("pvtsutils");
const asn1js = require("asn1js");
let base64 = "<your_csr_in_base64>"
let csrraw = utils.Convert.FromBase64(base64);
console.log(csrraw)
const pkcs10 = pkijs.CertificationRequest.fromBER(csrraw);
let seq = pkcs10.attributes[0].values[0];
let exts = pkijs.Extensions.fromBER(seq.toBER(false));
console.log(exts);
var san = getExtentionsForSANFromExtensions(exts);
console.log(san)
if (san != undefined) {
san.names.forEach(element => {
console.log(element.type + " = " + element.value)
});
}
function getExtentionsForSANFromExtensions(exts){
for (var i = 0 ; i< exts.extensions.length; i++) {
var ext = exts.extensions[i];
if(ext.extnID == '2.5.29.17') {
var octetString = asn1js.fromBER(ext.extnValue.toBER(false)).result;
return pkijs.GeneralNames.fromBER(octetString.getValue());
}
}
}
I've tested this code and it works properly with CSR generated by Keystore Explorer. Have not tested with another tool to generate CSR that supports subject alternative names.
Cheers!
If you have a CSR and need to extract the alternative names data from it, you can use the following command:
openssl req -in csr.pem -noout -text
This will print out the entire CSR, including the alternative names data.
I have some tables that have data and can using it on <td>. So more like it I have something like this (show on images below)
My Element
I want to get that all positions Name and put it into an array so I can make of use that array I tried to use this code and got undefined
script.js
/** Checking if There positions name */
function checkPositions(){
let positions = document.getElementsByClassName('check-positions').innerHTML;
let array = [];
array.push(positions);
console.log(array);
}
Then how can I get that value??
The problem that you have is that document.getElementsByClassName('check-positions') returns a HTMLCollection which does not have an innerHTML property.
What you need to do is convert the HTMLCollection into an array, and then read the innerHTML property for each of the items in the array. See the following example:
const elements = document.getElementsByClassName('check-positions');
const positions = Array.from(elements).map(element => element.innerHTML);
console.log(positions);
<div class="check-positions">1</div>
<div class="check-positions">2</div>
<div class="check-positions">3</div>
Use like this
let positions = document.getElementsByClassName('check-positions')[0].innerHTML;
It's showing none because u r fatching whole array and pushing it without using indexes
Code
function checkPositions(){
all_ele = document.getElementsByClassName('check-positions')
length = all_ele.length
let array = [];
for( let i=0;i<length;i++)
{
let positions = document.getElementsByClassName('check-positions')[i].innerHTML;
array.push(positions);
}
console.log(array);
you can use jquery code to do this.
var arr = [];
$("#tablePlacement tr").each(function() {
var name = $(this).children('td.check-positions').text();
arr.push(name);
});
You should use
let positions = document.getElementsByClassName('check-positions').innerText;
I am trying to disseminate the values over a repetitive property to set the contents of certain nodes. The way I'm doing it is effective. However, as I've mentioned, it's repetitive and kind of frustrating to look at. Is there any other way to shorten my codes?
for (var i = 0; i < 1; i++) {
var title = document.querySelector("h1.title"),
date = document.querySelector(".article-date"),
tme = document.querySelector(".article-tme"),
src = document.querySelector(".source"),
user = document.querySelector(".user"),
tip = document.querySelector(".tip");
//.....some other variables...
title.innerHTML = post[i].titles;
date.innerHTML = post[i].dates;
src.innerHTML = post[i].sources;
tme.innerHTML = post[i].times;
user.innerHTML = post[i].authors;
tip.innerHTML = post[i].excerpts;
//....some other HTML content setting...
}
...where "post" = JSON.parse(this.response);
Any kind of help to shorten this burden is appreciated. Thank you.
I'd use an object that maps the property names to selectors:
const selectorsByProp = {
titles: 'h1.title',
dates: '.article-date',
sources: '.source',
// ...
}
Object.entries(selectorsByProp).forEach(([prop, selector]) => {
document.querySelector(selector).innerHTML = post[i][prop];
});
Note that if the object values happen to contain plain text only, it would make a lot more sense to assign to the textContent of the element, rather than the innerHTML:
document.querySelector(selector).textContent = post[i][prop];
There's no need for the loop either, since you're just doing this once.
I am looking for some help, I am working on a piece of code for a client, the client currently have their analytics tag hardcoded to the page with all the key values being sent.
We are in the process of converting them to a new analytics platform using a tag management system, they have been able to update the majority of their platforms to create an object that the new analytics platform can reference but as this site is managed by a 3rd party they are unable to get this resolved in time for our release.
I have managed to successfully pull the tag and split the tag in to parameters:
var x = $('img[alt="MI_TAG"]').attr("src");
x.split("&");
Which creates the array:
1:"109=jsp.searchFlights.initial"
2:"117=Flight Only Journey"
3:"206=02/11/2017"
4:"208=03/11/2017"
5:"212=ALL"
What I want to do is take these array strings to create an object call "mi", like so:
109:"jsp.searchFlights.initial"
117:"Flight Only Journey"
204:""
205:""
206:"02/11/2017"
208:"03/11/2017"
Can someone help?
Thanks all for your help, I have managed to take some of the advice here and create the object and see it logging out:
var x = $('img[alt="MI_TAG"]').attr("src");
var split = x.split("&");
var arrayLength = split.length;
var arr = [];
var i = 0;
do {
arr.push(split[i].replace('=',':'));
arr.toString();
console.log(arr);
i += 1;
} while (i < arrayLength);
let mi = {};
arr.forEach(item=>{
let tempArr = item.split(':');
mi[tempArr[0]] = tempArr[1];
})
console.log(mi);
The issue I now seem to be facing is scope, I want my object to be globally referenceable, how do I do that?
From your array, use reduce - split on the = sign in your string, and create the object:
let newObject = arr.reduce((obj, item) => {
let parts = item.split("=");
obj[parts[0]] = parts[1];
return obj;
}, {});
Assuming you are using at least ECMAScript 5.1 you could use Array.prototype.forEach() to iterate over your array and produce the object.
let myArray = ["109=jsp.searchFlights.initial", "117=Flight Only Journey", "206=02/11/2017", "208=03/11/2017",
"212=ALL"];
let myObject = {};
myArray.forEach(item=>{
let tempArr = item.split('=');
myObject[tempArr[0]] = tempArr[1];
})
console.log(myObject);
Produces:
{
"109": "jsp.searchFlights.initial",
"117": "Flight Only Journey",
"206": "02/11/2017",
"208": "03/11/2017",
"212": "ALL"
}