how can I get all this array in one array without getting it one after the other like this in the code below? i mean saving the whole data inside one variable without giving a specific index of the array
here's the code
const favoriteProductone = data?.getAllLikeProduct[0]
const favoriteProductTwo = data?.getAllLikeProduct[1]
const favoriteProductThree = data?.getAllLikeProduct[2]
console.log(favoriteProductone?.Like[0])
console.log(favoriteProductTwo?.Like[0])
console.log(favoriteProductThree?.Like[0])
Just iterate the array like so:
if (!data) {
throw "data is falsy - there is nothing to process";
}
data.getAllLikeProduct.forEach(p => {
console.log(p.Like[0])
});
Related
I am very new to JavaScript and I am trying to use it to select values from HTML using document.getElementsByClassName by putting index [0] from HTMLCollection. There is either one instance of the class being present or two or more.
const pizzatype = document.getElementsByClassName("pizzapizza")[0].innerHTML;
const pizzacheese = document.getElementsByClassName("cheesecheese")[0].innerHTML;
const pizzasauce = document.getElementsByClassName("saucesauce")[0].innerHTML;
const ordertotal = document.getElementsByClassName("fiyat")[0].innerHTML;
const order_dict = {
pizzatype,
pizzacheese,
pizzasauce,
ordertotal
}
const s = JSON.stringify(order_dict);
console.log(s); // returns {"pizzatype":"value1","pizzacheese":"value2","pizzasauce":"value3","ordertotal":"value4"}
The class is set like this:
<div class="cheesecheese card-text">${pizza.cheese}</div>
I tried experimenting with for loop, index(), .length, and others but I never got it to work. What would be the way to go to get return:
{
"pizzatype": "valuex1",
"pizzacheese": "valuex2",
"pizzasauce": "valuex3",
"ordertotal": "valuex4",
"pizzatype": "valuey1",
"pizzacheese": "valuey2",
"pizzasauce": "valuey3",
"ordertotal": "valuey4"
}
It should work even when there are more than 2 instances of those classes.
There is no way to store same key multiple times in Javascript object. You can use Entries syntax instead to get something similar.
Example of entries
[
[“pizzatype”, firstval],
[“pizzatype”, secondval],
]
Or you can use array of values inside your object.
To get result like so
{
pizzatype: [firstval,secondval],
…
}
You can get it with this way
{
pizzatype: Array.from(document.getElementsByClassName(“pizzapizza”)).map(elem => elem.innerHTML)
}
I am trying to push data into array in this code
let eyesData = [];
const pushFaceData = (
{ rightEyeOpenProbability },
i
) => {
//Value is getting printed in console but not getting pushed
//console.log(rightEyeOpenProbability);
eyesData.push(rightEyeOpenProbability);
};
const renderFaces = () => {
faces.map(pushFaceData);
};
console.log(eyesData);
faces is stream of data that updates itself in every 100ms so eyesData array should also be getting populated on each 100ms but in console, eyesData is always getting printed with empty value.
Array[]
Array[]
.
.
If rightEyeOpenProbability is printing to the console, then there is no reason your code should be failing...
You are probably changing eyesData somewhere. For example, if you made a typo when checking its length, you could be erasing it:
if( eyesData.length = 0 ) { ... } //this line would erase eyesData[]'s contents
The issue I am having is displayed in the picture.
I am able to convert the strings into number type using map but when wishing to push to an array of numbers I am unable to. Also I am trying to maintain types but I believe this may be the issue but I am unable to make headway.Maybe I should create another variable and store the newly created number values into that array? Also when console logging I am just getting the single value as a number and not as an array.
openValues: string | number[];
I hope someone can please help...
getData() {
this.pricingService.getDailyPricing().subscribe((data) => {
this.dailyData = data;
const timeSeries = data['Time Series (Daily)'];
const dailyDates = Object.keys(timeSeries);
dailyDates.forEach((parentKey) => {
const parentValue = timeSeries[parentKey];
const childKeys = Object.keys(parentValue);
this.dailyDates = new Date(parentKey);
childKeys.forEach((childKey) => {
const keyName = childKey;
const keyValue = parentValue[childKey];
this.timeSeriesSeperationMethod(keyName, keyValue);
});
});
});
}```
The image attached contains the issue.
[![The Image of this issue able to convert to number but unable to push to an array of numbers][1]][1]
[1]: https://i.stack.imgur.com/pL1JA.gif
I have an object, with a list inside each key. What is the best way of returning the key, if the url string matches what's in the array.
For example in the code below, 'entertainment' would be returned as "/video" is in the entertainment array.
const url = "https://example.com/video";
const verticalList = {
autos:[],
entertainment:["/video", "/tech"],
foodanddrink:[],
healthandfitness:[],
homepage:["/home"],
lifestyle:["/ideas", "/executive-life"],
money:["/money-markets",],
news:["/briefing"],
sports:[],
travel:[],
weather:[]
}
You can use Object.entries to get a list of key-value pairs from your object and then run Array.filter to compare values against your url. In the last step you have to run Array.map to retrieve corresponding keys. String.includes can be used to check if one string is a substring of another.
const url = "https://example.com/video";
const verticalList = {
autos:[],
entertainment:["/video", "/tech"],
foodanddrink:[],
healthandfitness:[],
homepage:["/home"],
lifestyle:["/ideas", "/executive-life"],
money:["/money-markets",],
news:["/briefing"],
sports:[],
travel:[],
weather:[]
}
let matches = Object.entries(verticalList)
.filter(([key,value]) => value.some(x => url.includes(x)))
.map(([key,value]) => key);
console.log(matches)
In my ReactJS application I am getting the mobile numbers as a string which I need to break and generate a link for them to be clickable on the mobile devices. But, instead I am getting [object Object], [object Object] as an output, whereas it should be xxxxx, xxxxx, ....
Also, I need to move this mobileNumbers function to a separate location where it can be accessed via multiple components.
For example: Currently this code is located in the Footer component and this code is also need on the Contact Us component.
...
function isEmpty(value) {
return ((value === undefined) || (value === null))
? ''
: value;
};
function mobileNumbers(value) {
const returning = [];
if(isEmpty(value))
{
var data = value.split(',');
data.map((number, index) => {
var trimed = number.trim();
returning.push(<NavLink to={`tel:${trimed}`} key={index}>{trimed}</NavLink>);
});
return returning.join(', ');
}
return '';
};
...
What am I doing wrong here?
Is there any way to create a separate file for the common constants / functions like this to be accessed when needed?
First question:
What am I doing wrong here?
The issue what you have is happening because of Array.prototype.join(). If creates a string at the end of the day. From the documentation:
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
Think about the following:
const navLinks = [{link:'randomlink'}, {link:'randomlink2'}];
console.log(navLinks.join(','))
If you would like to use concatenate with , then you can do similarly like this:
function mobileNumbers(value) {
if(isEmpty(value)) {
const data = value.split(',');
return data.map((number, index) => {
const trimed = number.trim();
return <NavLink to={`tel:${trimed}`} key={index}>{trimed}</NavLink>;
}).reduce((prev, curr) => [prev, ', ', curr]);
}
return [];
};
Then you need to use map() in JSX to make it work.
Second question:
Is there any way to create a separate file for the common constants / functions like this to be accessed when needed?
Usually what I do for constants is that I create in the src folder a file called Consts.js and put there as the following:
export default {
AppLogo: 'assets/logo_large.jpg',
AppTitle: 'Some app name',
RunFunction: function() { console.log(`I'm running`) }
}
Then simply import in a component when something is needed like:
import Consts from './Consts';
And using in render for example:
return <>
<h1>{Consts.AppTitle}</h1>
</>
Similarly you can call functions as well.
+1 suggestion:
Array.prototype.map() returns an array so you don't need to create one as you did earlier. From the documentation:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
I hope this helps!