Get names and values from array in Javascript - javascript

I want to get the values of an array that looks like this:
t = new Object();
t.erg = new Array();
t.erg['random1'] = "something1";
t.erg['random2'] = "something2";
t.erg['random3'] = "something3";
t.erg['random4'] = "something4";
But i want to get the random names and then the values of them through a loop, I can't find a way to do it :/

You would use the other form of the for loop:
for (x in t.erg) {
if (t.erg.hasOwnProperty(x)) {
alert("key is " + x + " value is " + t.erg[x]);
}
}

To get a random value, you could get a random number and append it to the end of the string "random".
Something like this might work:
var randomVal = "random" + Math.floor(Math.random()*4);

To get the the names of something you would use a for in loop, but you are actually creating to objects not an object and an array. Why not use literals like this
t={
erg:{
'random1':'something1',
'random2':'something2'
}
}
for(var x in t.erg){
//in the first round of the loop
//x holds random1
}

Related

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

Putting geolocation coordinates into array

I'm trying to put my geolocation coordinates gathered during watchPosition() into an array, so that I can work out total distance later.
I have create a new array
var mapArray;
mapArray = new Array();
then where I assigning my latitude and longitude im putting the values to the array
document.getElementById("currentLat").innerHTML = (position.coords.latitude);
document.getElementById("currentLong").innerHTML = (position.coords.longitude);
document.getElementById("mySpeed").innerHTML = (speedValue.toFixed(1));
mapArray.push(currentLat);
mapArray.push(currentLong);//put values in array
I then want to output them to check it has worked so have tried converting the array to a string
function getArray(){
var outputData = mapArray.toString();
document.getElementById("arrayresult").innerHTML = (outputData);
}
Can anyone see where I'm going wrong at all?
At the moment the output is just 'HTML.SpanElement],[object' over and over again.
thanks.
If you want to use an array, don't use new Array(), use the array literal [] instead, and then we can just assign the whole thing in one go:
var mapArray = [
position.coords.latitude,
position.coords.longitude
];
But, since you already have that convenient position object, why not just rely on that:
function showPosition(position) {
// grab all the keys in position.coords
var keys = Object.keys(position.coords);
// and then map them to "key: value" strings
var pairs = keys.map(function(key) {
return key + ": " + position.coords[key];
});
// join them up with commas between them, and ONLY between them:
var stringified = pairs.join(", ");
// and then set that as our on-page container text
document.getElementById("result").textContent = stringified;
}
And of course we can tighten that since it's fairly straight forward code:
function showPosition(position) {
var result = Object.keys(position.coords).map(function(key) {
return key + ": " + position.coords[key];
}).join(", ");
document.getElementById("result").textContent = result
}
We're also using textContent here, just in case position.coords contains funny keys or values. Setting it as text content, rather than HTML content, means there's no content that can accidentally trigger.

Save and print list with array

I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.

Use javascript variable as array index

I have following code:
var n = 1;
var term = "${abc[n].term}";
console.log("term = " + term);
term seems to be empty, but if I replace
var term = "${abc[n].term}";
by
var term = "${abc[1].term}";
it works.
It looks like jsp is looking for the n property of the deck object, how could I fix it so that n is replaced by its value when I use is as array index ?
Edit:
It seems that it's not a good idea to try mixing JSTL and Javascript, and that if you want to use a javascript variable as array index, you must copy the object to an Array object, like this:
var deck = new Array();
<c:forEach var="v" items="${abc}">
deck.push("${v.term}");
</c:forEach>
var n = 1;
console.log("term = " + deck[n]);
You are not using quotes properly, try this:
var term = "${abc[" + n +"].term}";
"${abc[n].term}" here n is considred as a part of the string not as your variable n. So try concatenating it.

How make jquery loop over with number

I am trying to assign a number to my variable i.e. colorswap1, colorswap 2, colorswap 3
I have the following
var i = 1-36;
// Get current image src
var curSrc = $('#colorswap'[i]).attr('src');
It doesn't seem to be putting the desired: colorswap1, colorswap2
Your variable declaration is doing the algebraic subtraction and will result in -35. You need a loop of some sort. Then, you concatenate the index with the string using the + operator. Because one of the things is a string, it will concatenate instead of "add".
Below is an example of what you can do:
for (var i = 1; i <= 36; i++) {
var curSrc = $('#colorswap' + i).attr('src');
// now do stuff with curSrc here
}

Categories

Resources