When a user inputs text I want to create an array with the name of the inputted text and add it to array logNum. I've tried like this but it doesn't work:
logNum.push(var document.getElementById("buttonInput").value.toString()[]);
Any ideas?
Assuming you've yet created your logNum array, you can do this :
logNum.push([document.getElementById("buttonInput").value]);
The [something] notation creates a new array whose first element is something.
i'm not sure i understood you, but try this:
logNum.push( window[ document.getElementById("buttonInput").value ] = [] );
first, we generate out array: window[ document.getElementById("buttonInput").value ] = [] this creates an array with a user-input name.
and remember that assignments always returns the value of right-hand-side. so new array will be returned.
then, push the returned value to logNum array.
Related
I want to be able to create an array with only one value inside of it on the fly without using a variable. This works with a variable:
var arr = [];
arr.push('test');
console.log(arr); // correctly logs ["test"]
But this does not:
console.log([].push('test')); // logs 1
Why does this log 1 instead of ["test"]? Is this coerced into a boolean?
Array.prototype.push returns the new length of the array, not the pushed item nor the array it-self.
"I want to be able to create an array with only one value inside of it
on the fly without using a variable"
const arr = ['test'];
console.log(['test']);
Array.prototype.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
In the first example you are first pushing the element in the array then log the array. But in the second example you are logging the returned result of push().
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){}
This is sample JSON I got {"valueofa" : 1234}.To print the value it is something like body.valueofa. However, this valueofa can be anything like apple or something else. So to parse that I object I had tried with ${body}.${value} which isn't working and it's shouldn't be. How can I set the variable with body. So that I can parse the body whatever the value is.
If your object always contains only one key value pair like shown in the question, and you don't care about the key, you can just use Object.values()
console.log(Object.values({"valueofa" : 1234})[0]);
console.log(Object.values({"apple" : 1234})[0]);
The same is true for objects holding multiple key value pairs, Object.values() will return an array of all the values in your object if you omit accessing the first element with [0]
You can access a value of JSON using square brackets.
var value = "valueofa";
body[value];
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('')
For example,
{
id:"monday",
names:[
{one:"white", two:"pink"},
{uno:"blanco", dos:"rosado"}
]
}
How would you change white to black?
So far, I've got this:
r.db.table.get('monday').update({
names: r.row("names").nth(0)
})
Which specifies the 0th index of names, but not sure how to further specify the one field and then change it.
What you have so far is pretty correct but you replace names with its first sub-object (I guess you saw that result already).
You just need to use a merge to alter the sub-object, and a changeAt on names to put the altered sub-object in the array, just like this:
r.db.table.get('monday').update({
names: r.row('names').changeAt(0, r.row('names').nth(0).merge({one: 'black'}))
})
Hope this helps!
Maybe your data is stored in an object with the name of obj; something like
var obj = {...}
you can make this work:
obj.names[0].one = "black";
I have actually tried it using firebug no issues.
Each element in the array is independent so no worries.
First off all, you should use replace instead of update.
Get record without names field.
merge it with new names (remove 1st element from it, add at the 1st position new element in which we replaced white to black in one field)
Something like this:
r.db.table.get('monday').replace(function(doc){
return doc.without({names: true}). merge({
names: doc("names").deleteAt(0).prepend(doc("names").nth(0).merge({
one : "black"
}))
})
})