Loop through JSON object returned from cookie - javascript

I know there are a bunch of questions out there regarding this, but I have tried several different proposed solutions and get the same results for each one.
I am storing checkbox values in an array in the format timeArr = [ event-name-one: 0: 1404915600, 1: 1404917400 ]. When the array gets updated with a new key/value pair a cookie is updated which stores the array as a JSON object.
I am storing the JSON object in the cookie using jQuery.cookie('day', JSON.stringify(timeArr), {expires: 7}); which stores the array in the following format (returned from console.log();):
{"event-name-one":{"0":1405346400,"1":1405347600},"event-name-two":{"0":1405357200,"1":1405358400}}
In this instance event-name-one and event-name-two are the ID's of the checkboxes. I need to loop through the returned cookie value (JSON object) and check the checkboxes whos ID's are found in the returned cookie.
I have tried a few different loops, i.e. for(var k in cookieValue){} and jQuery.each(jQuery.parseJSON(cookieValue), function(i, v) {}); with no luck.
The for(var k in cookieValue) loop returns each letter of the object separately and the jQuery.each() loop returns this error: Cannot use 'in' operator to search for '76' in ...
How can I convert this JSON string back to an array so I can loop through it and get the 'keys'

jQuery.cookie() must stringify arrays automatically into JSON objects because in order to get the correct results from the loop I had to use jQuery.parseJSON() on the response twice.
Example:
var cookieVal = jQuery.cookie('day_planner');
jQuery.each(jQuery.parseJSON(jQuery.parseJSON(cookieVal)), function(i, v) {
console.log(i, v);
});
This loop returns event-name-one Object {0: "1405346400", 1: "1405347600"}

Related

Why do you have to loop through JSON data in order to retrieve JSON Values?

I was told that the reason I had to loop through JSON data is because JSON is an array. If that is true my question is why do you have to loop through JSON data in order to retrieve JSON Values? If that is not true is there another way to retrieve JSON data using jQuery? I added jQuery to my tag words because I would like to retrieve JSON data via jQuery. My JSON data is below:
[
{
"input":0,
"candidate":0,
"delivery":"one",
"last":"two",
"point":"none",
"fruit":{
"apples":"yes",
"oranges":"no",
"grapes":"yes",
},
"analysis":{
"code":"Y",
"crr":"TTB",
}
}
]
JSON stands for JavaScript Object Notation.
In JavaScript Objects are Associative Arrays. Associative Arrays map unique keys (could be a string, but could also be a number) to a value.
Normal arrays are actually subsets of Associative Arrays (they have only* number keys). Where each (unique) number maps to a value.
To get all the data out of an array you ask it for the value of each key. This is usually done with a loop. In the case of Associative Arrays that means looping over its keys (whatever type they might be), and asking for its value in the array, like so:
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
*Not completely true in JS, as length and some other things are actually also keys, which is also related to why you have to ask if a key is it's own property.

How to get id from array of Object?

I have data in response so here rcsaAssessmentData.data.lobCheckListDTOs is array , riskAsesCklstSessionKey is property of array , How can i get this key using filter or any other option.Below console is printing all objects but i just want value for the riskAsesCklstSessionKey.
So far tried code...
array.js
var opChecklist = rcsaAssessmentData.data.lobCheckListDTOs.filter(function(obj){
return obj.riskAsesCklstSessionKey;
console.log("opcheclist...............",obj.riskAsesCklstSessionKey);
});
$scope.challengesDTO.addChlngToChklst= obj.riskAsesCklstSessionKey;
This is what I think you mean:
You have an array of objects, rcsaAssessmentData.data.lobCheckListDTOs. Each of the objects in the array has a property called riskAsesCklstSessionKey. You are trying to get an array of those keys. If so, try this:
var keys = rcsaAssessmentData.data.lobCheckListDTOs.map(function(a) {return a.riskAsesCklstSessionKey;});

Iterate Through array inside object

Using C# regex i have sent modelState object to the java script and add it in the var type temp. Now this object have multiple arrays with in.
One way is to specify the key and get all error msgs from this object like
{{modelState["employee.FirstName"][0]}}
{{modelState["employee.Email"][0]}}
{{modelState[".............."][0]}}
There are almost 8 to 10 key pairs that maybe returns and will take time to write all key value. How do i iterate from this arrays inside object and get all the errors with out specifying the key value.
You could:
var allErrors = [];
$.each( modelState, function( name, errors ){
allErrors = allErrors.concat(errors);
} );

Iterate over jQuery JSON object in Chrome its changing the order

Jquery + rails 4
In json_data instance i have some data with key and value, The key is an integer id and the value is an object which contains data.However when I try to iterate over this data with the jQuery $.each function, the results come back sorted by the key instead.How can I iterate over my collection of objects in their original order?
$.each(json_data, function(key, value){
console.log(key);
});
key = 6181 30654 39148 30743 30510 42998 5788 30401 ...//Mozilla Working Fine (Right)
key = 5788 6011 6181 30401 30510 30639 30654 30698 30743 ...// Chrome Not Working Fine (Wrong)
Regarding "order" in an object:
A JavaScript object is a hash table, and is optimized for constant time lookup of key:value pairs.
Arrays are a data structure in which the elements are assigned to a discrete index value. When you iterate over the elements of an array, you will return a predictable pattern that matches the order of the items in the array.
In an object however, there are no index values, so there is no constant predictable way to iterate over it in order. The object just stores key:value pairs that are optimized for constant-time lookup.
EDIT: I will demonstrate those two methods of iterating just for illustration, but I wanted to warn you in advance, they won't change the fact that you won't get the keys returned in a consistent order.
var json_data = {6181:true, 30654:true, 39148:true, 30743:true, 30510:true, 42998:true, 5788:true, 30401:true};
for(item in json_data){
console.log(item);
} // *might* return a different order based on browser or JavaScript implementation
Clarifying one more time: objects are not associated with a particular 'order'. They are optimized to provide "constant time" lookup. Regardless of the size of the object, if you query a key, the associated value will be returned to you in constant time.
If you need to impose a particular order, you will need to use an array.
Example:
var json_data = [6181, 30654, 39148, 30743, 30510, 42998, 5788, 30401];
for(var i = 0; i < json_data.length; i++){
console.log(json_data[i]);
}
// always returns the values in the same order they are in the json_data array.
// changing the order in the array will change the order they are output and
// and that order will be the same regardless of which browser or version of JavaScript you
// are using.

How do I access this javascript object?

{"profit_center" :
{"branches":
[
{"branch": {"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3310","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3311","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3312","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3313","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3314","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3315","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}}
],
"profit_center_name":"Alabama"}}
I tried accessing it in ajax through this,
data.profit_center //data here is the ajax variable e.g. function(data)
or through this data["profit_center"]
but no luck
How do I access this javascript object properly. ?
By the way that code above is from console.log(data)
EDIT:
Result from console.log(data.profit_center) and console.log(data["profit_center"]) is undefined
You can put your datain a variable like
var json = data
and you can access profit_center like
alert(json.profit_center);
alert(json.profit_center.profit_center_name); //Alabama
for(var i =0 ;i<json.profit_center.branches.length;i++){
alert(json.profit_center.branches[i]);
}
Okay I have found out why it is undefined, It is a json object so I need to parse it before i can access it like a javascript object.
var json = JSON.parse(data);
Then that's it.
First parse your data if you've not already done so.
You can access, for example, each branch_number like so:
var branches = data.profit_center.branches;
for (var i = 0, l = branches.length; i < l; i++) {
console.log(branches[i].branch.branch_number);
}
In summary, profit_center is an object and branches is an array of objects. Each element in the array contains a branch object that contains a number of keys. Loop over the branches array and for each element access the branch object inside using the key names to get the values.
The profit center name can be found by accessing the profit_center_name key on the profit_center object:
console.log(data.profit_center.profit_center_name); // Alabama
You could even use the new functional array methods to interrogate the data and pull out only those branches you need. Here I use filter to pull those objects where the purchase_order is equal to 2. Note that the numeric values in your JSON are strings, not integers.
var purchaseOrder2 = branches.filter(function (el) {
return el.branch.purchase_order === '2';
});
DEMO for the three examples

Categories

Resources