each() with counter - const names - javascript

I am trying to loop through some HTML elements, extract the content and set them as a const value with the index number like this...
jQuery('.myitems').each(function (index) {
const myitem + index = [jQuery(this).text()];
console.log(myitem + index);
});
This is not working, can anyone tell me the correct way to achieve?

You can use object instead of count. And your code will be broken.
See the following solution.
jQuery('.myitems').each(function (index) {
const count = {}
count[myitem + index] = [jQuery(this).text()];
console.log(count[myitem + index]);
});

Shouldnt you store the values in an array instead?
const myitem = [];
jQuery('.myitems').each(function (index) {
myitem[index] = jQuery(this).text();
console.log(myitem[index]);
});

You cannot do what you're attempting in JS. An alternative would be to populate an array with the values by using map():
var arr = $('.myitems').map(function() {
return $(this).text();
}).get();
If you still want to use the 'myitem' + index prefix on the values then you could instead use an object:
var obj = {};
$('.myitems').each(function(i) {
obj['myitem' + i] = $(this).text();
});

Here, I have first set constant and then on looping I have set value with index number. Currenlty , I have made output on console. You can check it. Let me know if you do not understand
const staff=[];
$('.staff').each(function(index){
staff[index]=$(this).text();
})
console.log(staff);

Related

Concat In JavaScript

For some reason the keyText variable isn't showing any value when it should concat for each variable in keywords.
When someone clicks the button it runs addKeyword and grabs the value of the input.
Tried to Console.Log the keyText variable and didn't work at all.
var keywords = [];
var keyText = "";
function addKeyword() {
var keywordName = document.getElementById("keywordAdd").value
keywords.push(keywordName);
keywords.forEach(showKeywords);
function showKeywords(item, index) {
var newString = "<span class='keyword' onclick='delKeyword(" + index + ")'>✖ " + item + "</span>";
keyText.concat(newString);
document.getElementById("keywords").innerHTML = keyText;
}
}
No Errors shown in Console. Expected result is a list of but doesn't show.
The problem is that .concat doesn't mutate the string, it returns a new string.
You need to do something like this:
keyText = keyText.concat(newString);
By the way, your current approach is not that efficient because it changes the element's inner HTML at each iteration. You should probably do that only once after the HTML for all the elements is generated. Here is another approach that does that:
const result = keywords.map((item, index) => (`<span class="keyword" onclick="delKeyword(${index})">✖ ${item}</span>`)).join('');
document.getElementById("keywords").innerHTML = result;
Titus answer is correct, but you can simply use :
keyText += newString;

jQuery move value to last position

I have the object as,
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
Now i have to move the value which contains "Num" to the last which means after the "Num" value there should be no values.
This is how i add the value to the array,
result.each(function () {
var tempObject = {},
attributes = $(this).data();
names.push(attributes.prefix+ '_' + attributes.value)
});
Can i somehow manipulate the above code to make the "Num" values move at last.
I need something like,
var names =["LET_ABC","PET_DEF","SET_GHI","RET_JKL","Num_123","Num_456"];
for(var i=0;i<names.length;i++){
if(names[i].match("^Num")){
names.push(names.splice(i, 1)[0]);
}
}
Working example (with explanation in comments):-
var names =["LET_ABC","LET_DEF","Num_123","Num_456","LET_GHI","LET_JKL"];//your array
function movetoLast(names,checkword){// function with array and checking prefix
$(names).each(function(index,value){ // iterate over array
if(value.indexOf(checkword) >= 0){ // check value have that prefix or not in it
names.push(names.splice(names.indexOf(value), 1)[0]); // if yes move that value to last in array
}
});
return names; // return modified array
}
var names = movetoLast(names,"Num");// call function
console.log(names); // print modified array in console
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this.simple use Array#filter and Array#concat
var names = ["LET_ABC", "PET_DEF", "Num_123", "Num_456", "SET_GHI", "RET_JKL"];
console.log(names.filter(a => !a.match(/(\d+)/g)).concat(names.filter(a => a.match(/(\d+)/g))))
I would put the numbers in a separate array to concatenate the two arrays at the end.
result.each(function () {
var tempObject = {}, attributes = $(this).data();
var numsArray = [];
if (attributes.prefix==Num){
numsArray.push(attributes.prefix+ '_' + attributes.value);
}else{
names.push(attributes.prefix+ '_' + attributes.value)
}
names.concat(numsArray);
});
Use push to add a value to the end of an array if it has the "Num" prefix and use unshift to add a value to the beginning of an array if it does not have the "Num" prefix. Working code:
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
$(document).ready(function(){
result_array = [];
$.each(names, function(index, value){
if (value.substring(0,3)=="Num"){
result_array.push(value);
} else{
result_array.unshift(value);
};
});
console.log(result_array);
});

making JSON from string

I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}

Getting undefined in dropdown from json content

EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

Categories