I have my form field values in an immutable object.
I use getIn immutable function to access it.
For example, if I have to access field, i use const users = formFields.getIn(['0', value]).
Now, i have a variable
users = 4`
This means, there will be 4 fields in immutable from which i need to pick up the users age.
e.g.
1st user age will be stored in formFields.getIn(['1', value])
2nd user age will be stored in formFields.getIn(['2', value])
and so on
How do i loop through the user age list based on the users variable?
I tried something like this:
const userAgeList = [];
if (users >0) {
userAgeList.push(formFields.getIn([[i], value]));
}
With above code formFields.getIn([[i], value]), i get undefined because the value is not actually on this. its on formFields.getIn(['i', value]).
How do i pass the loop variable i as a string so i can get the field values?
If what you have is a List containing Map objects, you can use a map to loop all the values:
const userAgeList = formFields
.map(field -> field.get('value'))
.toArray()
This will give you an array of the values you need.
If you want to take only at a specific i, convert it to a number and then you can combine skip and take in this fashion:
const userAgeList = formFields
.skip(i)
.take(1)
.map(field -> field.get('value'))
.toArray()
This will return you a one element array at the i position.
Related
I don't think I'm very far from the answer, I tried to query an id inside an array on Firestore.
I wanna compare the id of the participants.
Also my DB in Firestore:
And also my function, for the moment my function return size =0 so they can't catch the query.
const deleteAbuse = (type) => {
const participants = channel?.otherParticipants;
if (!participants || participants.length != 1) {
return;
}
const myID = currentUser.id;
const otherUserID = participants[0].id;
console.log('id user', otherUserID);
channelDB
.where('participants.id', '==', otherUserID)
.get()
.then((querySnapshot) => {
console.log(querySnapshot.size);
querySnapshot.forEach((doc) => {
console.log(doc.ref);
//doc.ref.delete();
});
});
};
There is no way you can query filter your "channels" collection to get documents based only on a single field of an object that exists inside the participants array. In other words, you cannot create that filtering based only on that ID. To be able to filter the data, you should pass to the where() function, the entire object, and not only some partial data. The object should contain values for all the fields. Only the ID is not enough.
And also my function, for the moment my function return size =0
That's the expected behavior since in your array there isn't any object that holds only a single field called id. All objects hold 7 fields, or even more than that, as I cannot see all fields in your screenshot.
I wrote an article called:
How to update an array of objects in Firestore?
Where you can find in the first part, the simplest way to get a custom object from an array of custom objects.
Alternatively, you can create an array that can hold only the IDs of the participants, filter the documents and create another database call to get their corresponding data.
I'm trying to code a notification system but I'm having issues with a problem so I have a function named getAlerts that return an array like this:
[{"id":3,"user_id":"1","asset":"xyz","price":600,"position":"above"},{"id":4,"user_id":"1","asset":"xyz","price":300,"position":"above"}]
Then I have a websocket with setInterval that keeps checking the value every 1 second how do I compare the price string from websocket to all the price key in the array with regard to their user_id key? let's say that the current price matches one of the price key in the array how do I get the index of the matched key? I've done lot of Googling but unfortunately those questions compared two arrays and still couldn't find anything on getting the index of the matched key.
NodeJS Code
const main = (ticker) => {
let list = [];
if (assetprice > list) {
// get user_id of matched key
// do something
}
};
You can use Array.prototype.findIndex to find the index of the first matching element using a predicate. Alternatively, use Array.prototype.find to immediately get the result:
const data = [ 'ABC123', 'DEF456', 'ABCDEF123456' ];
const index = data.findIndex(v => v.includes('DEF'));
console.log(index); // 1
const value = data.find(v => v.includes('DEF'));
console.log(value); // 'DEF456'
I'm simply using strings and String.prototype.includes as data/predicate, but this can also work with your list of objects where you check e.g. v.user_id === user_id.
I am building a program on node.js that scans the prices of some currencies, and I am getting the prices, however I would like the program to also log the name of the currencies, not just the price. As you can see in the following code, the 'currency' variable in the console.log was my try to make the name show before logging the price.
const currencies = [euro, yen];
for (let currency of currencies) {
const pair = await fetchPairData(currency, dollar);
const route = new Route([pair], dollar);
console.log(currency + route.midPrice.toSignificant(6));
}
But it seems like the currency variable wants to return the values associated with it, not the names of the currency... How do I switch that?
Thanks for the help guys, step by step I will get good at this!
As soon as you do this:
const currencies = [euro, yen];
there is no link from currencies[0] back to euro or from currencies[1] back to yen. [euro, yen] takes the value of the euro and yen variables and puts those values in the array.
Trying for minimal changes to what you have, you could use an object rather than an array:
for (let [currencyName, currencyValue] of Object.entries({euro, yen})) {
const pair = await fetchPairData(currencyValue, dollar);
const route = new Route([pair], dollar);
console.log(currencyName, currencyValue + route.midPrice.toSignificant(6));
}
How that works:
{euro, yen} is an object literal using shorthand property notation; the longhand would be {euro: euro, yen: yen}. So you end up with an object with properties named "euro" and "yen" with the values from the euro and yen variables.
Object.entries creates an array of [name, value] pairs from an object's own enumerable properties. The array ends up being :
[ ["euro", euroValue], ["yen", yenValue] ]
(You could, of course, just do that directly rather than via Object.entries({euro, yen}).)
for-of loops through the entries in that array.
I'm using destructuring assignment in the for-of to grab the name and value into separate constants.
But, ideally you'd change your starting point so you had pairs of names (of the currency) and values (the currency value) to start with, rather than creating them based on variable names.
I have a React application which handles rooms and their statistics.
Previously, I had the code set up to pass as props to the next component:
the raw statistics (not a concern for the question)
an array of all the rooms set up as follows
I figured it would be simpler for me, though, to have the list of all rooms as an associative array where the keys of each element is the same as the ID it contains. To do that, I utilized a code similar to this in a for loop:
roomsList[rooms[v].ID] = rooms[v];
So that the result would be:
[a001: {...}, a002: {...}, ...]
I then proceeded to pass this style of array, and not the standard one with a numeric index, as a prop to the next component as such:
<StatsBreakdown stats={computedStats.current} roomsList={roomsList} />
BUT
Now, the next component sees that prop as an empty array.
Even more weirdly, if I initialize that roomsList array with a random value [0] and then do the same process, I end up with:
I cannot cycle through the array with .map, and, according to JS, the length is actually 0, it's not only Google Chrome.
Is there something I'm missing about the way JSX, JS or React work?
Your original roomsList was an array of objects, whose indices were 0,1,2 etc. roomsList[rooms[v].ID] = rooms[v]; implies you are inserting elements not using a number but an alphanumeric string. Hence your resulting array is no longer an array but an object.
So we can cycle over the object using Object.keys().
const renderRoomDets = Object.keys(roomsList).map(room => {
roomOwner = roomsList[room].owner_id;
return (
<div>
<p>{`Room Owner ${roomOwner}`}</p>
</div>
);
});
But I believe your original form is ideal, because you are reaping no special benefits from this notation.
A better alternative maybe using .find() or .findIndex() if you want iterate over an array based on a specific property.
const matchedRoom = roomsList.find(room => room.ID === 'Srf4323')
Iterate the new array using its keys not indexes.
Or even better store your data in an actual object instead of an array since you're using strings for ids.
First define your object like so:
let data = {};
Then start adding records to it. I'd suggest deleting the ID attribute of the object since you're storing it in the key of your record, it's redundant, and it won't go anywhere unless u delete the entry.
data[ID] = row;
To delete the ID attribute (optional):
row.ID = null;
delete row.ID;
Then iterate through it using
for(let key in data){}
Using my micro:bit I am trying to add the value of a variable called sendText to an array without overwriting its previous stored value for that variable.
input.onGesture(Gesture.Shake, () => {
list.push(sendText)
binSend = 0
basic.showString(sendText)
})
My array is called list
let list: string[] = []
I am trying to store single characters in an array then outputting them. If there is a better alternative to using an array I would gladly accept it.
To add a value to an array you use push function, after, if you need to group the characters pushed to array for output you could to use for your specific example list.join('')