jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx
Related
I'm looking to extract the values 'adult' and '2ndclass' from this custom javascript array in separate javascript variables for each value. Anyone has any ideas on how to do this?
In the following case, there are 2 products added to cart but I would like to have the flexibility to always grab any existing values for each product that is added to cart regardless of the amount added. Is that possible?
[
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**',
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**'
]
Thank you in advance for your help
You can also use RegExp to get those values out.
var arr = [
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**",
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**"
];
var results = [];
for (var i=0; i < arr.length; i++) {
var matches = arr[i].match(/\*\*(.+)\/(.+)\*\*/);
if(matches && matches.length >= 3)
results.push([matches[1], matches[2]]);
}
console.log(results);
You can try the code here https://jsfiddle.net/p84eftL7/1/
First of all i didn't get your question completely. But as far as i can understand you want those 2 values at the end of the strings from an array. You can try something like this
var a, b;
for(s in YOUR_ARRAY){
[...other, a, b] = YOUR_ARRAY[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
Let me explain myself, Firstly you would require to iterate over your array thats why we have a 'for' loop here. Then for each string which is given by 'YOUR_ARRAY[s]' you are splitting the string with '/' as a delimiter. Rest of the thing is pretty simple.
For your reference go through these links
https://www.w3schools.com/js/js_loop_for.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
UPDATE:
As mentioned in the comments. If you want to have a function for this then
function processValues(arr){
var a, b;
for(s in arr){
[...other, a, b] = arr[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
}
processValues(YOUR_ARRAY);
In the end what I did was the following
As I had to reference back to the name of the variable I used the following to slice up the array so I could reference that using index numbers for the values I needed to retrieve:
function() {
var myStringArray = {{MY_ARRAY}};
var arrayLength = myStringArray.length;
var output = []
for (var i = 0; i < arrayLength; i++) {
var string = myStringArray[i].split("/",4)
/*pull index 2 and 3 from string and convert to string*/
output.push(string)
}
return output
}
After that I had to loop the new array that was being pushed out of the info as mentioned above
Since I only needed to split up particular indices from that NEW_ARRAY_2, I used the following to do that
function() {
var products = {{NEW_ARRAY_2}};
var arr = []
for (var i=0; i < products.length; i++) {
var prod = products[i];
var matches = prod[2];
arr.push(matches);
}
var list = arr.join(', ')
return list
}
SAMPLE RETURN for 2 products: 'adult, youth'
Thank you for your support
I have an array that the values range from A to Z, which I want to convert to variables that depend on the input data, for example:
enter the data
362,232,113 and this becomes an array of a length of 3 unit.
so I want to assign the name of a variable depending on the length of the input array but when executing the code, it assigns the array index well, but that same index executes the length of the input array and does not assign the variables as I would like it to.
in fact when executing this happens:
(3) 326
showing that the matrix was correctly divided but the same index was executed 3 times, in summary what I want is to be executed as follows:
"A = 326" "B = 232" "C = 113"
In advance I thank you for your help
var asignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
matrix =[326,232,113];
function divide(){
xyz = matrix.split(",");
console.log(matrix);
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
console.log(A); //(2) 326
}
}
You have a typo assignLetter instead of asignLetter ( two s ) and you need to pass a string to your function for it to work :
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
}
}
console.log({A,B,C});
You should avoid creating global variabels like that, have them in an object instead
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
var myVars = {};
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
myVars[assignLetter[i]] = xyz[i];
}
}
console.log(myVars);
I think you want to pass the parameters 326,232,113 as a whole string. You're passing them as parameters wrong.
So just do the same thing you're doing but like this: divide("326,232,113")
I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0
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);
}
I'm trying to populate an array from a JSON feed. My code looks something like this:
// multiple arrays
var linje_1 = []
var linje_2 = []
// loop from json feed to populate array
for( var i = 0; i < data.length; i++) {
// I'm trying to "build" the array here. I know for sure that data[i] is good value that match the suffix of the array.
arrayname = 'linje_'+data[i];
arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })
}
Does anybody have any suggestions on how to solve the above?
The problem is that the code will not accept arrayname, but if I change and hardcode linje_1, everything works as expected.
When you define a variable arrayname = 'linje_'+data[i]; then its type is String. Strings are not arrays, you can't treat them like array, they don't have array methods.
If you want to dynamically construct the name of the variable, the best thing you can do is to use object and its keys:
var lines = {
linje_1: [],
linje_2: []
};
for (var i = 0; i < data.length; i++) {
var arrayname = 'linje_' + data[i];
lines[arrayname].push({ label: data[i].x_ + sid[a], y: data[i].y_ + sid[a]});
}
Also note, that I cleaned up the code a little (things like data[i].x_ + '' + sid[a] + '').
You're pushing data to a String, not an array. Try this:
window[arrayname].push(/* ... */);
if your variables are declared in the scope of the window, they can be referenced in multiple manners:
myArray
window.myArray
window['myArray'] // You want this one
You're using the same variable for an array and string.
arrayname = 'linje_'+data[i];
arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })
The variable arrayname is defined as a string, but then you call the push method which is only a method for arrays.