Display elements in my 2d Array in Javascript - javascript

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

Related

Access the nested value in JSON without looping through it

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)

Access Array of Objects after filtering

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.

Convert JSON into array dataType

I have the following JSON string
var json = {"result":[{"address":" Ardenham Court, Oxford Road ,AYLESBURY, BUCKINGHAMSHIRE ,UNITED KINGDOM","picture":"1.jpg","uniqueid":"8b54275a60088547d473d462763b4738","story":"I love my home. I feel safe, I am comfortable and I am loved. A home can't be a home without our parents and our loved ones. But sad to say, some are experiencing that eventhough their loved ones are in their houses, they are not loving each other. There is a big war. You can't call it a home."}]}
I want to get address ,picture,story separately
for accomplish this. I tried recent answers in stackoverflow, but I was not able to achieve it.
Below is what I have tried,
$.each(json.result.address, function (index, value) {
// Get the items
var items = this.address; // Here 'this' points to a 'group' in 'groups'
// Iterate through items.
$.each(items, function () {
console.log(this.text); // Here 'this' points to an 'item' in 'items'
});
});
Try this:
$.each(json.result, function (index, value) {
console.log(this.address); // this will give you all addresses
console.log(this.picture); //this will give you all pictures
console.log(this.uniqueid); //this will give you all unique id's
console.log(this.story); //this will give you all stories
});
DEMO
If u want it in array then u can use split function like below
var address=json.result[0].address.split(",");
var picture=json.result[0].picture.split(",");
var story =json.result[0].story.split(",");
if there are more the 1 result in json then
var address=[];
var picture=[];
var story =[];
for (var i=0;i<json.result.length;i++){
address=address.concat(json.result[i].address.split(","));
picture=picture.concat(json.result[i].picture.split(","));
story =story .concat(json.result[i].story.split(","));
}
you can try this:
for(x in json.result){
alert(json.result[x].address);
alert(json.result[x].picture);
alert(json.result[x].uniqueid);
alert(json.result[x].story);
}

How can I parse a JSON object containing a colon

I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)

jQuery add text before final element of an array

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");
}
}

Categories