How to get this running ? Need to pass the itens id in the path to have access to product node, how can I do this ?
const itens = db.ref();
const eanRef = itens.child('cart').child('itens/{id}').child('product');
To replace the value of an integer variable id to a string itens/{id} you can do the following:
var id = 15;
const itens = db.ref();
const eanRef = itens.child('cart').child('itens/'+id.toString()).child('product');
Use javascript template literals.
const id = 'id-whatever'
const itens = db.ref();
const eanRef = itens.child('cart').child(`itens/${id}`).child('product');
Related
I'm in a bit of a pickle. I'm running a forEach loop for an API that will create a new div for each result with some html appended inside it. While the data is being retrieved, it appends only to the first div created. I'm trying to ensure each set of text ends up in each individual div. Can anyone enlighten me on what I'm doing wrong? Thanks
app.displayResults = (arrayOfObjects) => {
arrayOfObjects.forEach((Object) =>{
const number = Object.house_number;
const address = Object.street_name;
const zipCode = Object.zip_code;
const borough = Object.borough;
const date = Object.inspection_date;
const initial = Object.inspection_type;
const iResult = Object.result;
const resultContainer = document.createElement("div");
resultContainer.classList.add('resultContainer');
document.querySelector('.inspectionResults').append(resultContainer);
const innerHTML = `
<p class = "recordDetails"> ADDRESS: ${number}${address}</p>
<p class = "recordDetails"> DATE: ${date}</p>
<p class = "recordDetails"> BOROUGH: ${borough}</p>`
const record = document.createElement("div");
record.classList.add('record');
record.innerHTML = `${innerHTML}`
document.querySelector(".resultContainer").append(record)
})
}
In the last line of your forEach callback, you're querying the first .resultContainer element instead of the one you've created before. Instead of immediately appending that div to the DOM, append your record to resultContainer, then append only resultContainer to the DOM, like this (I've changed Object to obj because Object is already defined):
app.displayResults = (arrayOfObjects) => {
arrayOfObjects.forEach((obj) =>{
const number = obj.house_number;
const address = obj.street_name;
const zipCode = obj.zip_code;
const borough = obj.borough;
const date = obj.inspection_date;
const initial = obj.inspection_type;
const iResult = obj.result;
const resultContainer = document.createElement("div");
resultContainer.classList.add('resultContainer');
const innerHTML = `
<p class = "recordDetails"> ADDRESS: ${number}${address}</p>
<p class = "recordDetails"> DATE: ${date}</p>
<p class = "recordDetails"> BOROUGH: ${borough}</p>`
const record = document.createElement("div");
record.classList.add('record');
record.innerHTML = `${innerHTML}`
resultContainer.appendChild(record); // instead of directly appending record to document append it to the container, then append the container to the document
document.querySelector('.inspectionResults').append(resultContainer);
})
}
app.displayResults = (arrayOfObjects) => {
arrayOfObjects.forEach((obj) =>{
/*
const number = Object.house_number;
const address = Object.street_name;
const zipCode = Object.zip_code;
const borough = Object.borough;
const date = Object.inspection_date;
const initial = Object.inspection_type;
const iResult = Object.result;
*/
// Destructuring Assignment maybe better here
const { house_number : number,
street_name : address,
zip_code : zipCode,
borough,
inspection_date : date,
inspection_type : initial,
result : iResult } = obj
const resultContainer = document.createElement("div");
resultContainer.classList.add('resultContainer');
// below is the problem, you appended several divs with the class name 'resultContainer', every time you query, there were a array of it, and you always got the first.
// document.querySelector('.inspectionResults').append(resultContainer);
const innerHTML = `
<p class = "recordDetails"> ADDRESS: ${number}${address}</p>
<p class = "recordDetails"> DATE: ${date}</p>
<p class = "recordDetails"> BOROUGH: ${borough}</p>`
const record = document.createElement("div");
record.classList.add('record');
record.innerHTML = innerHTML
// here just append to the exact div you created above
resultContainer.append(record)
// then append the container which contains the content you expected to the documment
document.querySelector('.inspectionResults').append(resultContainer);
})
}
How about adding an identifier?
terms.setAttribute(‘id’,‘para-1’);
I am trying to get the first segment of the path from a string.
Current Behaviour:
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/')[1];
const resultTwo = pathTwo.split('/')[1];
const resultThree = pathThree.split('/')[1];
console.log(resultOne, resultTwo, resultThree);
As you see in the above code, I tried split the string and get second element from the array which has the first segment of the path.
But unfortunately in the last one, I get query params along with it, which I intend to remove it and get only tasks for all three strings.
Kindly please help me with efficient way of achieving the result that gives only the first segment of the path and ignore query params.
Note:
Please don't consider it as url and it is just a normal string with pathname and I am intend to get only the first segment of it tasks .
You can do somethong like this
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const getFile = fullPath => {
const [path, query] = fullPath.split('?')
return path.split('/')[1]
}
console.log(getFile(pathOne));
console.log(getFile(pathTwo));
console.log(getFile(pathThree));
You have index key after .split() -> [1]. When you have key index, you told "Give me first separated word from string"
If you remove it, you can get every string separated by "/". Try :)
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/');
const resultTwo = pathTwo.split('/');
const resultThree = pathThree.split('/');
console.log(resultOne, resultTwo, resultThree);
EDIT: IF you don't wanna query parameters, you must split "pathThree" string also by "?"
If you're getting the string from the window object you can obtain the pathname from the window.location property
const pathParts = window.location.pathname.split('/');
Otherwise you can construct an URL object
const myUrl = new URL('https://www.example.com/get/the/pathname?param=1¶m=2');
const pathParts = myUrl.pathname.split('/');
If you're working on a path string (not a valid url) I'd suggest something like
const myStr = '/get/the/pathname?paramA=1¶mB=2';
const parts = myStr.split('?')[0].split('/');
enter code hereconst pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/')[1];
const resultTwo = pathTwo.split('/')[1];
const resultThree = pathThree.split(/[/?_]+/)[1];
console.log(resultOne, resultTwo, resultThree);
Is there any way to create variable from String inside the array with the name of the String?
something like this:
const array = ["type","name","hours","photos","place","price"];
array.forEach(item =>{
let item = document.crea.....
//but it should work like let array[index] = docu.......
})
The reason for this is that I wanted to make this code look a bit nicer and its obvious, that there are quite a lot things repeating.
const type = document.createElement("td");
const name = document.createElement("td");
const hours = document.createElement("td");
const photos = document.createElement("td");
const place = document.createElement("td");
const price = document.createElement("td");
type.innerHTML = element.type;
name.innerHTML = element.name;
hours.innerHTML = element.hours;
photos.innerHTML = element.photos;
place.innerHTML = element.place;
price.innerHTML = element.price;
tr.appendChild(type);
tr.appendChild(name);
tr.appendChild(hours);
tr.appendChild(photos);
tr.appendChild(place);
tr.appendChild(price);
Try use var or let instead const,works for me always.
And remember foreach is a kind of loop means
var mytd = document.createElement("td");mytd.innerHTML = element.{item};tr.appendChild(mytd);
I know this doesn't directly answer your question about variable names, but this should be the code you need to get your result.
array.forEach(item => {
const elem = tr.appendChild(document.createElement("td"));
elem.innerHTML = item;
})
You don't really need to use your array to generate the variable name as the forEach handles each item in the array separately.
I want to get and store id from idArray to use each id indvidual
I tried to store in session storage but it return the last element
success: function (data) {
const myText = "";
const addressArray = [];
const titleArray = [];
const typeArray = [];
const idArray = [];
data.map((user) => {
addressArray.push(user.address);
titleArray.push(user.title);
typeArray.push(user.jtype);
idArray.push(user.id);
});
container.innerHTML = "";
for (let i = 0; i <= 3; i++) {
let clone = row.cloneNode(true);
container.appendChild(clone);
container.firstChild.innerHTML = "";
jobtitle.innerHTML = data[i].title;
jbtype.innerHTML= typeArray[i];
jbaddress.innerHTML= addressArray[i];
sessionStorage.setItem('jobid',idArray[i]);
}
}
The issue I can see is , since the key is always same , it is overriding the value of the same key.
You can instead do something like
sessionStorage.setItem("jobid-"+i,idArray[i]);
This should solve the problem for sure.
It returns the last value because you are using the same key to store each value. Try using a different key for each or alternately, create an array of ids using map function and store the array in session with the key 'jobid'.
You can serialize and store it in session as follows:
sessionStorage.setItem('jobid', JSON.stringify(idArray));
To read the same back out you can use code like
JSON.parse(sessionStorage.getItem('jobid'));
I'm trying to get an item in array which contains a specific value.
Let's say I have an array
var arr = ["boat.gif", "goat.png", "moat.jpg"];
And I have a variable var imageName = "boat"
Since I do not know the file extension of imageName, I need a way to run it through my array and get "boat.gif" as the output.
I tried this with regular expressions
let filesString = arr.join(" ");
let regExName = new RegExp(imageName, "i");
let fileName = regExName.exec(filesString),
file = fileName.input.substr(fileName.index, 5);
It works but I'm hoping there's a better way
I hope this makes sense
Might be easier to filter by .includes or .startsWith instead:
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const found = arr.find(str => str.includes(imageName));
console.log(found);
or
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const found = arr.find(str => str.startsWith(imageName));
console.log(found);
If there might be other files in the directory which start with the same word (like boats.gif), then construct a regular expression like you're doing, but lookahead for a .:
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const pattern = new RegExp(imageName + '(?=\.)');
const found = arr.find(str => pattern.test(str));
console.log(found);