javascript or jquery: Looping a multidimensional object - javascript

I just started playing around with JSON and I have created this example.
var shows = {
"ShowA":
{ "Date" : "November 3-5, 2011",
"Phone" : "111-111-1111",
"Location" : "some location",
"url" : "http://www.showA.com"
},
"ShowB":
{ "Date" : "January 15-18, 2012",
"Phone" : "222-222-2222",
"Location" : "another location",
"url" : "http://www.showB.com"
}
};
I figured out how to access each bit of information...ie: alert(shows.ShowA.Date);
However, I can't figure out how to loop the entire shows object in order alert each show and each show's properties. Do I need to change it to an array?
Any help would be greatly appreciated.

you can use a for ... in loop:
for(var key in shows) {
if (shows.hasOwnProperty(key)) {
alert(shows[key].Date);
}
}
It's important to note that an object has no sort order, but an array does. So if you wanted to sort by dates, you would need to use an array.
Also it's good practice to use Object.hasOwnProperty

for(show in shows){
console.log(shows[show]);
}
Fiddle: http://jsfiddle.net/maniator/Wp3N9/
No extra libraries needed ^_^

Related

How to avoid numeric come first alignment Issue while converting string data to json array through Json Parse in Jquery

Here is the sample code of returning string data from ajax
Result = "[
{"ProductCode":"0000001",
"ProductName":"BRINJAL LONG (GREEN)",
"HQ":"43.00",
"1104":"0.00",
"4758":"20.00",
"5379":"23.00",
"964":"2.00",
"ActualQty":"0.00",
"IsCheck":"True"}
]"
I am converting string to json array through Json parse sample code here
var myproduct = []; myproduct = JSON.parse(Result);
Actually i need output like same as string return alignment order but i am getting like this numeric comes first. kindly give some advice how to avoid this auto alignment
'{964: "2.00",
1104: "0.00",
4758: "20.00",
5379: "23.00",
ProductCode: "0000001",
ProductName: "BRINJAL LONG (GREEN)",
HQ: "43.00",
ActualQty :"0.00",
IsCheck : "True"
}'
you should change your data shape, JavaScript JSON.parse() doesn't let you to control that.
a silly solution is to add a counter to the key names. it's bad because later you need to do some string manipulation to remove the counter
Result = "[
{"1.ProductCode":"0000001",
"2.ProductName":"BRINJAL LONG (GREEN)",
"3.HQ":"43.00",
"4.1104":"0.00",
"5.4758":"20.00",
"6.5379":"23.00",
"7.964":"2.00",
"8.ActualQty":"0.00",
"9.IsCheck":"True"}
]"
or change the value part and add an order item. this way you can sort things again using that order value
Result = "[
{
"ProductCode":{
"value": "0000001"
"order": 1
},
"ProductName":{
"value" : "BRINJAL LONG (GREEN)",
"order" : 2
},
....
}]"
or a better solution would be to send an array of single key-value object. this way the parse of the json, will keep the order of the array. then each item has key and value.
Result = "[
{"ProductCode":"0000001"},
{"ProductName":"BRINJAL LONG (GREEN)"},
{"HQ":"43.00"},
{"1104":"0.00"},
{"4758":"20.00"},
{"5379":"23.00"},
{"964":"2.00"},
{"ActualQty":"0.00"},
{"IsCheck":"True"}
]"
a much better solution will be to set a key for each item, it's much easier to work with without need to use Object.Keys() to get the key value.
Result = "[
{ "key" : "ProductCode", "value" :"0000001"},
{ "key" : "ProductName", "value" :"BRINJAL LONG (GREEN)"},
{ "key" : "HQ", "value" :"43.00"},
{ "key" : "1104", "value" :"0.00"},
{ "key" : "4758", "value" :"20.00"},
{ "key" : "5379", "value" :"23.00"},
{ "key" : "964", "value" :"2.00"},
{ "key" : "ActualQty", "value" :"0.00"},
{ "key" : "IsCheck", "value" :"True"}
]"
but this question just give me a hint that your problem is somewhere else. because you are relying on the order of the data. this way of coding, your code will fail when one of these items go missing, or some more get add to it.

How to create a Hashtable in javascript from a JSON by setting a value as the key?

I apologize if this is too vague, But I want to search each JSON object by a unique value and then spit out another value. I have been told it would be a good idea to create a Hash Table for this issue, but I do not know how to go about this. For example:
{
"form_key" : "basicPatientName",
"data" : "Miranda Jones",
"cid" : 2,
"pid" : 1,
"no" : "0"
}
I want to search basicPatientName and be able to pull Miranda Jones, or search basicPatientgender and pull 1.
I used a library called DefiantJS which lets me easily loop through my JSON and lets me do exactly what I am asking, but I have been told that there are too many iterations involved if I want to do this 1000+ times in the same program.
You could use this:
data = [{
"form_key" : "basicPatientName",
"data" : "Miranda Jones",
"cid" : 2,
"pid" : 1,
"no" : "0"
},
{
"form_key" : "basicPatientGender",
"data" : "1",
"cid" : 4,
"pid" : 1,
"no" : "0"
}
];
var result = {};
data.forEach(function (rec) {
result[rec.form_key] = rec.data;
});
// output result
console.log(result);
// Example look-up use:
var data = result.basicPatientName; // = Miranda Jones

Make use of unnamed array

I am calling an API and successfully getting back an array like this:
[ {
"absmag" : "4.85",
"speed" : "0",
"colorb_v" : "0.65",
"label" : "Sun",
"appmag" : "-26.72",
"distance_light_years" : "0",
"id" : "53794",
"hipnum" : "0",
"vy" : "0",
"updated_at" : "49:09.3",
"vx" : "0",
"vz" : "0",
"texnum" : "1",
"plxerr" : "0",
"created_at" : "49:09.3",
"plx" : "0",
"dcalc" : "0",
"z" : "0",
"luminosity" : "0.8913",
"y" : "0",
"x" : "0"
}
]
How can I reference each of these lines? I'd like to do something like:
var database = xml.responseText;
console.log(database.label);
xml.responseText is an array, you need to access on the the good index before show label :
var database = xml.responseText;
console.log(database[0].label); // Add [0] because your example is an array of one element if you have more index refer to the edit
If the response is a string, you need to parse the response before use it :
var database = JSON.parse(xml.responseText);
console.log(database[0].label);
Edit :
If your array has more than one index, you can use a foreach loop :
database.forEach(function(el) {
console.log(el.label);
})
The key to the answer actually lies in your question . . . that value IS an array . . . a single element array, whose only element is an object. As such, you have to access the array element like an array (i.e., with an index) and then, since that lone array element is an object, you have to access the object's properties like an object (i.e., with keys).
Using your example code, that would be: console.log(database[0].label); . . . [0] gets you the first (and only) element of the database array and .label gets you the value of the "label" property of that object.
If I understand it correctly, you are expecting the resulting array to contain not just one object as depicted by your original question, but it can contain a number of objects.
If that is correct then extending the correct answers by #R3tep, #talemyn and #trjast, a loop on top of this array should help as well, IMHO.
var database=xml.responseText;
var length=database.length;
for(var i=0;i<length;i+=1){
console.log(database[i].label);
}
Useful?
You could reference the label value with
var database = xml.responseText[0];
console.log(database.label);

MongoDB, PHP and JavaScript

I have the following document in a MongoDB 2.0.4 and PHP 5.5*
{
"children" : [
{
"name" : "openGL::gl"
},
{
"name" : "openGL::interfaces"
},
{
"name" : "openGL::picking"
},
{
"name" : "openGL::objects"
}
],
"name" : "test"
}
Using php I want to create another collection having a copy of this document.Because I cannot use php mongo::command I am just getting a cursor for the first collection and insert this cursor into the second:
$cursor = $collection->find();
foreach($cursor as $document){
$result->insert($document);
};
$collection is the original and $result is the new one.
Now the strange thing is sometimes this works perfectly and sometimes I recieve the following:
{
"children" : {
"3" : {
"name" : "openGL::objects"
},
"0" : {
"name" : "openGL::gl"
},
"1" : {
"name" : "openGL::interfaces"
},
"2" : {
"name" : "openGL::picking"
}
},
"name" : "test"
}
And this is really bad because I am trying to get those infos into Javascript and therefore the first one (the original) is an Array whereas the second one is an object with properties.
Does somebody know why I get this and how to fix it?
So this is the solution I am using now!
$db->command(array(
"eval" => new MongoCode("function(){
db['".$toCopy."'].copyTo('".$newName."')
};"
)
));
You can copy a collection on the server with the .copyTo() method for the collection:
db.collection.copyTo("new")
There is no client transfer as there is currently being done by iterating.
If for some reason you want this to be a part of your code then there is the "runCommand" option which has a longer syntax. So in PHP code, do the longer version of this with "eval":
$db->command(array(
"eval" => new MongoCode("function(){ " .
"db.collection.find().forEach(function(doc) { " .
"db.newcollection.insert(doc); " .
"}); " .
"};"
);
));
That will run the copy on the server. Take care to read the documentation and warnings on db.eval(). And aside from all else, but much the same as you were doing, then you must re-create all indexes on the target collection that you want to use.
But in general this will be a better way than iterating over a client connection.
Have you tried to sort the cursor like:
$cursor = $collection->find();
$cursor = $cursor->sort(array('name_of_key_variable' => 1)); //sorts in ascending order
foreach($cursor as $doc) {
...
}
You might also try more of the MongoCursor options listed here:
http://www.php.net/manual/en/class.mongocursor.php at the table of contents

Read complex JSON in pure Javascript

I have the following json object and I would like to read it (access some data from it)
how can I do it in Javascript please ?
var allSites =
{"oldSites":
[
{
"site0" : "http://site0.com/",
"site1" : "http://site1.com/",
"site2" : "http://site2.com/"
}
],
"newSites":
[
{
"site0" : "http://site0/new",
"site1" : "http://site1/new",
"site2" : "http://site2/new"
}
]
};
This is what I did but I get undefined.
var allSites = eval(allSites);
alert(allSites.oldSites.site0);
Thanks.
If your object is defined like you have described, it is not JSON, you do not need to use eval.
Then, since oldSites is an array, you have to index it, like oldSites[0] to get the first value.
Then, get the site0 key of the object retrieved.
So you should use: allSites.oldSites[0].site0
Use
allSites.oldSites[0].site0
allSites.oldSites is an array. So you have to iterate using index
Please remove the square brackets which make oldSites an array
var allSites =
{"oldSites":
{
"site0" : "http://site0.com/",
"site1" : "http://site1.com/",
"site2" : "http://site2.com/"
}
,
"newSites":
{
"site0" : "http://site0/new",
"site1" : "http://site1/new",
"site2" : "http://site2/new"
}
};

Categories

Resources