I have the following code.
function sendData(){
console.log($(".MultiFile-title").text())
}
And the result from multiple titles is:
file1.txtfile2.txtfile3.txt
What I need is the output to be
file1.txt, file2.txt, file3.txt
I believe the a FOR EACH loop would be best here but how would I write it to get the text from each div with the class name "MiltiFile-title" any help?
You could try:
function sendData(){
var result = [];
$('.MultiFile-title').each(function () {
result.push($(this).text());
});
result = result.join(', ');
console.log(result);
}
This creates a temporary array and loops through all the ".MultiFile-title"s on the page, pushing each items text onto the array.
After it's completed looping, it joins the strings together using the string ", " as glue.
You can try:
jQuery(".MultiFile-title").map(function(i, v){return jQuery(v).text().trim()});
Related
I have a function "zoom" which takes the following format:
zoom( [a,b,c,d....], [a,b,c,d...] );
I also have a for loop which gets me the values that need to go into the zoom array:
ABC.getAggregation("V")[0].getItems().forEach( function (item) {
var a = item.getPosition().split(";")[0];
var b = item.getPosition().split(";")[1];
ABC.zoom( [...], [...] );
});
How can I add variables a and b into the arrays of function zoom?
All variable a's must go into the first array and all variables b must go into the second.
Example:
ABC.getAggregation("V")[0].getItems()
//returns a list of 3 objects
item.getPosition()
//returns e.g "0,0,0" for the first item and so on (for all 3)
item.getPosition().split(";")[0] = "0"
//now i want to add this to the zoom function.
var a = item.getPosition().split(";")[0];
//this produces three string values "14.5". "4", "8.64"
var b = item.getPosition().split(";")[1];
//this produces three string values "5.7","6.8","1"
Now, I want to put these string values into zoom like this:
ABC.zoom( [14.5. 4, 8.64], [5.7,6.8,1] );
//note - they're not strings anymore.
How can I achieve this result?
You cannot execute the call to ABC.zoom() inside the .forEach() loop, since you'll only get the whole data set once all iterations have been executed.
I think you need something along those lines:
var zoomA = [],
zoomB = [];
ABC.getAggregation("V")[0].getItems().forEach( function (item) {
var a = item.getPosition().split(";")[0];
var b = item.getPosition().split(";")[1];
zoomA.push(Number(a));
zoomB.push(Number(b));
});
ABC.zoom(zoomA, zoomB);
Please let me know if I somehow misunderstood what you are trying to do.
Split return an array of strings, so item.getPosition().split(";")[0]; will return a string, not three strings. You need to split it again with , delimiter, parse the result array to int (you can use map function) and pass to zoom function.
This is my JSON, I want to directly get the zipCodes values from the JSON without looping through the JSON. How can I do it?
countries:[
{
name:'India',
states:[{
name:'Orissa',
cities:[{
name:'Sambalpur',
zipCodes:{'768019','768020'}
}]
}]
}
]
I think you are looking for
countries[0].states[0].cities[0].zipCodes
Please note, this works for the above JSON as there is only 1 country in countries array and same as for states and cities. However, if there are more than 1 country, state or city then, you will have to iterate to extract information until and unless you know the exact index.
As this is not an associative array, your option is only to use indexes like this:
countries[x].states[y].cities[0].zipCodes
Where x would be each representation of state in your array, in case, of course, that you have more than one.
Similarly y would be each state in each state in each country, in case you have more of those and you can do the same for cities if you need to.
EDIT:
Here's how you can iterate the array:
for(var c in countries)
{
var name = countries[c].name;
if (name === "CountryIAmLookingFor")
{
var statesList = countries[c].states;
for (var s in statesList)
{
var stateName = statesList[s].name;
.....
}
}
}
You can keep iterating until you find the country, state, and city you need, then extract the zipCodes from there as shown in the previous code snippet.
Without "looping"
You can do this crazy trick (not saying this is the best way, but this way you aren't looping through the JSON):
var myData = { 'Put Your Data': 'HERE' };
function getCodes(name, data) {
var sv = data.match(new RegExp(name+'([\\S\\s]*?}][\\S\\s]*?}])'))[1].match(/zipCodes":\[(.*?)\]/g), r = [];
sv.forEach(function (item) {
item.match(/\d+/g).forEach(function (sub) {
r.push(+sub);
});
});
return r;
}
getCodes('India', JSON.stringify(myData));
If your data is already string, then you don't need the JSON.stringify. The forEach you see isn't actually "looping" through the JSON. It's already extracted the zip codes and the code just adds the zip codes to the array. . This line:
var sv = JSON.stringify(data).match(new RegExp(name+'([\\S\\s]*?}][\\S\\s]*?}])'))[1].match(/zipCodes":\[(.*?)\]/g), r = [];
is what grabs the zip codes, it gets something like:
["zipCodes":["768019","768020"]"]
The next line:
item.match(/\d+/g)
will grab the numbers outputting something like:
["768019", "768020"]
The loop just adds the zip-codes to another array
With looping
You're better off looping through the JSON:
var myData = {}, // Your data
zips = [];
myData.countries.forEach(function(i) {
if (i.name === 'India') {
i.states.forEach(function(j) {
j.cities.forEach(function(l) {
l.zipCodes.forEach(function(m) {
zips.push(m);
});
});
});
}
});
//use "zips" array
PERFORMANCE AND SPEED TESTS
After testing copying an array about 500MB (half a gig) took about 30 seconds. That's a lot. Considering an extremely large JSON would be about ~5MB, looping through a little over 5MB of JSON takes about 0.14 seconds. You should never worry about speed.
Here's my "trick" for avoiding explicit iteration. Let JSON.parse or JSON.stringify do the work for you. If your JSON is in string form, try this:
var array = [];
JSON.parse(jsonString, function (key, value) {
if (key === "zipCodes") {
array = array.concat(value);
}
return value;
});
console.log(array); // all your zipCodes
Suppose your Json is like
countries =[
{
name:'India',
states:[{
name:'Orissa',
cities:[{
name:'Sambalpur',
zipCodes:768019768020
}]
},{
name:'mumbai',
cities:[{
name:'rea',
zipCodes:324243
}]
}]
}
]
So now we use MAP it will give you ZipCode of every cities
countries.map(function(s){
s.states.map(function(c){
c.cities.map(function(z){
console.log(z.zipCodes)
})
})
})
OR
If you use return statement then it will give you 2 array with two zip code as per over JSON
var finalOP = countries.map(function(s){
var Stalist = s.states.map(function(c){
var zip = c.cities.map(function(z){
return z.zipCodes
})
return zip
})
return Stalist
})
console.log(finalOP)
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.
I have an array:
var countryArray = [];
That I'm dynamically inserting values to with click events:
(on click...)
countryArray.push("Australia");
and then finally appending to a div for output:
$('#summary-countries').append(countryArray+'');
So my output could be:
Australia,United Kingdom,Finland,Japan.
Is there any way how I could insert some text so that it would output as the following:
Australia,United Kingdom,Finland **AND** Japan.
Any help would be appreciated!
Here's one way:
var countries;
if( countryArray.length > 1 ) {
var last = countryArray.pop();
countries = countryArray.join(', ')+' and '+last;
}
else {
countries = ''+countryArray;
}
$( '#summary-countries' ).append( countries );
Yes, there is a way. You are relying on the built-in serialization of arrays, when you call .append(reasonsTravelling+'');. This converts reasonsTravelling into a string, which, by default is a comma separated list.
You have to use a for loop instead and go through all the items in the array. Once you find that the iterator is one before the last index, use the "And" instead of ",".
This fiddle should explain my idea: http://jsfiddle.net/v76Bf/
You can traverse through and array and find the last index and insert the text before the last value.
for (var i=0;i<countryArray.length;i++)
{
if(i==countryArray.length-1)
{
countryArray[i].join(,).push("And");
}
}
I have a post function that returns a 2d array. How would I go about displaying each of the elements in it? My code looks something like this :
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(result) {
//$("#CustomerList tbody").append($(result));
var myarray = new Array()
myarray = result;
alert(myarray);
});
what the alert returns is "System.String[][]". How can i go about appending each of the values from my array to my div tag called #divComparativeQuestions.
For example:
var data = new Array();
for(var i=0;i<myarray.length;i++){
data.push(myarray[i].join(', '));
}
$('#divComparativeQuestions').html(data.join('<br/>'));
(hope this works, not tested :), but you get the idea )
I'm guessing you want something like:
// given an array [[1,2],[3,4]] with a desired result of <div>1234</div>
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(data) {
if(data) {
var div = $('#divComparativeQuestions');
$.each(data, function(index, element) {
div.append(element); // will be inner array of [1,2] or [3,4]
});
}
});
All pretty basic stuff, in this case I'm taking advantage of the fact js typically flattens array as strings without commas to get the desired out put, but if you want to delimit them items somehow or wrap them in tags or whatever, it's easy enough to work out by taking a few seconds to browse http://docs.jquery.com