Related
{"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
This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.
First try at using JSON. I have an ajax/php function that returns a JSON object. Back on the js side, I can see the object and output it to a div. It looks fine. I can print it to the console, still looks good. But when I try to iterate over it and expose the individual values, I just get 'undefined' in my console. I can't figure out what I am missing. Sorry it if's something obvious, but I don't see it. Thanks!
var jsonObj = JSON.parse(xmlhttp.responseText);
console.log(jsonObj); //<--looks perfect
console.log(jsonObj.length);
document.getElementById("rightsidebox").innerHTML=response; //<--looks good
for (var group in jsonObj) {
//each of these generates 'undefined' WHY???
//I get 4 'undefined' outputs for each group, so I know that my loop is iterating correctly
console.log(group.id);
console.log(group.day);
console.log(group.time);
console.log(group.name);
}
EDIT: Here is an example of one of the JSON objects being returned by my ajax call. In this example, I only have a single object inside of the array. Of course, there will typically be multiple objects:
[{"id":"7","day":"Thursday","time":"7:00 a.m.","name":"Sub 10:00"}]
EDIT 2: Given this array, I have to ask what the point of JSON is. I can return this array without having PHP encode it in JSON format. So, if all that comes back is just a javascript array, then what have I accomplished? Why not skip the JSON encoding in PHP and then iterate over the array? Clearly there is a reason for this, so I'm obviously missing something. Is there a better way to do what I am trying to accomplish? Thanks!
Consider the following:
var myJson = '{"groupA": {"id": 123, "name": "foo"}}';
var myObj = JSON.parse(myJson);
for (var i in myObj) {
console.log(i);
console.log(i.id);
console.log(myObj[i].id);
}
The expected output here is:
myGroup
undefined
123
This is because you loop is just assigning the 'key' of your object to the value i. If you were to iterate an array, instead of an object, you'd get indices instead of strings.
In the example JSON you've given, you have an array with one object in it. If you intend to have multiple objects in your array, something like this would be better:
for (var group in jsonObj) {
var thisGroup = jsonObj[group];
thisGroup.id; // Etc etc..
}
If you have the correct jsonObj, and you say that you do, you can use formatting to output the object in an easy to read form. You don't have to loop through it.
console.log(JSON.stringify(jsonObj, null, 1));
Not sure why this works, when my original for (var group in jsonObj) loop doesn't, but whatever...
for (var i=0; i < jsonObj.length; i++) {
console.log(jsonObj[i].id);
console.log(jsonObj[i].day);
console.log(jsonObj[i].time);
console.log(jsonObj[i].name);
}
I am trying to create number of arrays like _temp0[],_temp1[],_temp2[] so on and I want to store values of data[] in it.
so value of data[0] goes in array_temp0[] after splitting,
data[1] goes in _temp1[] and so on
to elaborate more-
If value of data[0] is string a,b,c
then array _temp0[] should be
_temp0[0]=a
_temp0[1]=b
_temp0[2]=c
I wrote this function
for(var k=0;k<data.length-1;k++)
{
window['_temp' + k] = new Array();
alert("actual data -- >"+data[k]);
'_temp'+k= data[k].split(',');
alert("data after split -- >"_temp[k]);
}
but it is not working, how do I solve it?
You can do the same using javascript objects. Here is an example of how to do it.
Create an object of name '_temp':
var _temp = {};
When you iterate through 'data' variable then, you can dynamically add attributes to it,say _temp['data0'], _temp['data1'] etc, and every attribute will be an array. For that, you need to write something like:
for(var k=0;k<data.length-1;k++)
{
_temp['data'+k] = data[k].split(',');
}
This will not create the variables identical to what you want. However, this is similar to what you want.
used
window['_temp'+k]= data[k].split(',');
instead of
'_temp'+k= data[k].split(',');
and it worked, thanks to go-oleg
is there any way I can get the return of $.getJSON into a variable array?
I know its async and out of scope, but I will use it inside ajax callback, I just need to get all the values first and check them against another array.
Something like:
$.getJSON('itemManager.php?a=getItems', function(data){
// itemArray = new Array(data);
// idsArray = new Array(data.id);
for (var i in someOtherArray){
if($.inArray(i, idsArray) == -1){
// do something...
// get jason variable by id?
// itemArray[i].someVariable
}
}
}
EDIT: JSON structure
[{"id":"786","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"787","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"785","user_id":"1","seller_id":"2","address_id":"1","time":1299852114,"publicComment":null,"personalComment":null},
{"id":"784","user_id":"1","seller_id":"2","address_id":"1","time":1299852113,"publicComment":null,"personalComment":null},
{"id":"783","user_id":"1","seller_id":"2","address_id":"1","time":1299852111,"publicComment":null,"personalComment":null}]
This is basically the idea.
Get all the values
Isolate the id values of JSON objects
Loop another array
Check if json id is inside the other array
Access other json variables by id value
There are various solutions here I guess, but I'm looking for something with minimal code.
With the given information, there is not shortcut to test the existence of IDs. You really have to loop over everything. However you can improve a bit by creating an id => object mapping:
$.getJSON('itemManager.php?a=getItems', function(data){
var items = {};
for(var i = data.length; i--; ) {
items[data[i].id] = data[i];
}
for (var j = someOtherArray.length; j--; ){
var item = items[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
It woud be even better if you create this structure on the server already, then it would be:
$.getJSON('itemManager.php?a=getItems', function(data){
for (var j = someOtherArray.length; j--; ){
var item = data[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
You should also consider which arrays will contain more elements, data or someOtherArray and adjust your data structures such that you loop over the smaller array only.
Update:
To create the appropriate structure on the server with PHP, you have to create an associate array.
So at the point where you add an object to the array, you should not do
$items[] = $obj;
but
$items[$obj->id] = $obj; // or $obj['id'] if you have an array
If you get an array as your JSON response then your data variable in your callback is an array, no need to do anything with it.
If you get an object as your JSON response as the data.id in you example might suggest, and some of it's values is an array, then just use data.id as an array, or use var array = data.id; if that is more convenient for you.
Remember that data in your callback is just whatever you got as JSON. It can be an object (which is an associative array), an array, a string, a number, or a true, false or null value. If it is an object you access it using data.key, if it is an array you access it using data[index]. I say it because I suspect that you might be confusing arrays with objects here.