I have a string with currency values. I add those values to a new array like so:
console logged number values
var xxc = 5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13;
var m = new Array(xxc);
For some reason, when the array is formed, it adds double quotes around my array and it breaks my array when trying to read it.
["5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13"]
I've tried to map the values in the array to remove the string using:
m.map(s => eval('null,' + s));
But that doesnt work. How would i remove the quotes in the array?
Your first line isn't well formed you need something like...
var xxc = [5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13];
You really don't need to reassign it.
var m = xxc;
You can check to see if it's in the correct format by logging to console.
console.log(m);
var xxc = [5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13];
var m = xxc;
console.log(m);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
Try this:
var xxc = [] ;
xxc = JSON.parse ([5868281.01, 5915961.10, 5748198.74, 5734639.29, 1144897.13]);
console.log(JSON.strigify(xxc) ;
To test, try:
console.log(xxc[2]) ;
and you should get: 5748198.74.
Related
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);
}
}
This is my input as string
'controls: ["aa.bb.cc","dd.ee.ff"],elements: []'
I want to get the result of the data in the controls meaning :
"aa.bb.cc","dd.ee.ff"
I tried pattern
/.*(controls:.*).*/
but I didn't get all the result
I think my problem is becuase the new line
You can do it with regEx
var c = 'controls: ["aa.bb.cc", "dd.ee.ff"], elements: []';
var match = c.match(/("[a-z.]+")/g);
// or c.match(/([a-z][a-z][.][a-z][a-z][.][a-z][a-z])/);
// to strictly match letters . letters . letters
// or for a shorter match: c.match(/(\w+[.]\w+[.]\w+)/);
console.log(match); // an array of your values
EDIT:
if you only want to get the values in controls and not element, you can get the controls values out with the regEx /controls: ([\["a-z., \]]+,)/g
You could simply parse your input as a JSON object then loop throught the controls array:
var input='controls: ["aa.bb.cc", "dd.ee.ff"],
elements: []';
json = JSON.parse(input);
var controls=json.controls;
//then loop throught the controls values
for(var i=0;i<controls.length;i++){
console.log(controls[i]);
}
I think that should do it.
This might look like a very crude solution, but it works.
This expression will give you aa.bb.cc :
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[1]
and this will give the next element i.e. dd.ee.ff
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[2]
In general,
var str = "controls: [\"aa.bb.cc\",\"dd.ee.ff\"],elements: []";
var resLength = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/).length;
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/);
for (var i=1; i<resLength; i++) {
console.log(res[i]);
}
I've got this string which needs to be converted to an array:
var string = "[[Restaurants], [Restaurants], [Restaurants], [Caterers, Foods - Take-out]]";
I then need to be able to access its value like so:
var foo = arr[0]; //returns "Restaurant"
var bar = arr[3]; //returns "Caterers, Foods - Take-out"
I tried removing the first and last characters ( "[" and "]" ) but I was still left with a problem when splitting on "," because some of the value have commas inside them. Any ideas?
You could use a combination of the split method and the map method. split creates the array and map cleans it up by returning a new Array:
var string = '[[Restaurants], [Restaurants], [Restaurants], [Caterers, Foods - Take-out]]';
var items = string.split('],').map(
function(s) { return s.replace(/(\[\[| \[|\]\])/g, ''); }
);
http://jsfiddle.net/4LYpr/
Since you are splitting and trying to make an array first remove the first("[[") and last ("]]") then split the string by ("], [").
Easy:
> a = "[[Restaurants], [Restaurants], [Restaurants], [Caterers, Foods - Take-out]]"
> b = a.slice(1).split(",")
> newB = []
> for (i=0;i < b.length;i++) {
formatted = b[i].trim().slice(1,-2);
newB.push(formatted);
}
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.
I am trying (in Javascript an Coldfusion) to convert:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"},
Into this:
{ member,book,journal,new_member,cds}
Notice that I am trying to eliminate quotes.
Is it possible to achieve this? How can I do it?
Ok, so this:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
is JSON.
To convert to a CF struct, you'd go like this:
myStruct = deserializeJSON('{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}');
(Note my examples assume we're operating within a <CFSCRIPT> block.)
Now you've got a simple struct with key/value pairs. But you want a list of the values. So let's make an empty string, then append all the struct values to it:
myList = "";
for (k IN myStruct) {
myList = listAppend(myList,myStruct[k]);
}
Boom. myList should now be "member,book,journal,new_member,cds"
Wrap it in curly braces if you really want to.
myList = "{"&myList&"}";
First of all, I have to thank you for your replies. But some of you have to be more polite with newbies.
var tata = {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
var arr=[]
for (var i in tata) {
arr.push(tata[i])
};
console.log(arr);
wrd = new Array(arr)
var joinwrd = wrd.join(",");
console.log('{' + joinwrd + '}');