Please explain .each loop in Jquery - javascript

I am new to Jquery. I am calling a Struts 2 action which return a Json object.
I dont understand how actually .each function works in Jquery.
Can you please explain how can I use the variable data, in a complex json using jquery.
{
"od": {
"cwd": [
{
"batchCount": 140,
"batchId": "2121",
"countryName": "Mexico",
"processId": "210002",
"status": "F",
"timeRequired": 140
},
{
"batchCount": 140,
"batchId": "8259",
"countryName": "Japan",
"processId": "220002",
"status": "F",
"timeRequired": 140
}
],
"percentageCompleted": 100,
"remainingTime": "-104Hours -4Mins",
"successBatchCount": 0,
"totalBatchCount": 920
},
"processDateInput": "19/11/2014" }
So here is what I wanted to know that
if json data is parsed into var obj,
Can cwd be accessed by :
var cwd = result.od.cwd;
$.each(cwd, fuction(index, value)){
var batchcount = value.batchcount;
});
and likewise can we parse any json string in jquery.
Thanks and regards,
Tushar

For basic understanding , explain you with your example,
First parent object has two object , "od" and "processDateInput" you can get the values of object directly like od.percentageCompleted , od.remainingTime, processDateInput etc..
So if there is an array inside an object then you need to go for $.each or for loop ,example
$.each(od.cwd,function(index,element){
/*index will be 0 and element will have first cwd[0] value {
"batchCount": 140,
"batchId": "2121",
"countryName": "Mexico",
"processId": "210002",
"status": "F",
"timeRequired": 140
}*/
//similar to this you can get the value
var batchCount=element.batchCount;
});

Related

RethinkDB javascript to java query

I am fairly new to RethinkDB, so I was able to create my query in JavaScript the problem now is to translate this query into the Java language.
Can someone with more experience help me please?
r.db('reval').table('measurements').filter({ measurementId: 1478261131038})
.update(function(measurement){
return r.branch(measurement.hasFields('movingObject'),
{ movingObject: measurement('movingObject').append({'x': 10, 'y': 40})},
{ movingObject : [{'x': 0, 'y': 0}]}
)})
UPDATE:
After some help from ... I was able to insert the first object of the array. The problem now is when I want to keep inserting more elements.
I start with this record:
{
"from": null ,
"id": "c94aa215-a47e-4cd0-8f98-1b69d7e93a1d" ,
"measurementId": 1478273740811 ,
"movingObject": null,
"time": null ,
"userObject": null
}
After calling this query:
MapObject myArray = new MapObject().with("x", 20).with("y", 80);
MapObject myArray2 = new MapObject().with("x", 10).with("y", 40);
HashMap run = r.db("reval").table("measurements")
.filter(measurement -> measurement
.g("measurementId")
.eq(1478273740811L))
.update(measurement ->
r.branch(
measurement.hasFields("movingObject"),
r.hashMap("movingObject", measurement.g("movingObject").append(myArray)),
new MapObject().with("movingObject", myArray2)
)).run(connectionFactory.createConnection());
The result was this:
{
"from": null ,
"id": "c94aa215-a47e-4cd0-8f98-1b69d7e93a1d" ,
"measurementId": 1478273740811 ,
"movingObject": {
"x": 10 ,
"y": 40
} ,
"time": null ,
"userObject": null
}
Now when I want to insert another element into my array (in this example {{"x": 20, "y": 80}}) the Java code gives the following error:
{
deleted=0,
inserted=0,
unchanged=0,
replaced=0,
first_error=Expected type ARRAY but found OBJECT.,
errors=1,
skipped=0
}
Can anyone give me some pointer on how to solve this problem, because I think we are very close to the solution.
Something like this:
r.table("measurements")
.filter(measurement -> measurement.g("measurementId").eq(1478261131038L))
.update(measurement -> r.hashMap("movingObject", r.branch(measurement.hasFields("movingObject"),
measurement.g("movingObject").append(r.hashMap("x", 10).with("y", 40)),
r.array(r.hashMap("x", 0).with("y", 0)))));

How to create an JSON array like this in javascript

What is the best way to create an array that looks like the following:
[
{
"id":"1",
"value": true
},
{
"id":"3",
"value": false
},
{
"id":"5",
"value": true
},
{
"id":"6",
"value": false
},
{
"id":"9",
"value": true
},
]
My code:
//add to array
thing = {
"id" : 1,
"value" : "true"
};
thingArray.push(thing);
It does not seem to be properly formatted when I put the output in a JSON validator.
As I commented further up, make sure you're actually serializing it to JSON at some point. In your code example you're simply working with a JavaScript object, which isn't the same thing as JSON. Here's an example:
// start with a regular JavaScript array
var array = [];
// push some regular JavaScript objects to it
array.push({
id: 1,
value: true
});
array.push({
id: 2,
value: false
});
// serialize your JavaScript array into actual JSON
var json = JSON.stringify(array);
// do whatever you want with it...
console.log(json);
Here's a JSBin example.
Your code is fine. Here's some more code to get you started:
var arr = [];
arr.push({"id": 1, "value": "true"});
arr.push({"id": 2, "value": "false"});
console.dir(arr);
http://jsfiddle.net/gg014w0h/
You can run that fiddle and then check your console output. You'll see the contents of the array pretty clearly.
JSON validators will not like the trailing comma of the array. There is a difference between console.log(array) and console.log(JSON.stringify(array)). You may want to use the latter.
Also note that booleans are allowed in JSON:
"value": "true",
"value": true
Those are both valid and they mean different things.

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

push syntax in Javascript for an array within an array

"elements": [
{
"values": [
{
"value": 70
}
],
"dot-style": {
"dot-size": 2,
"halo-size": 2,
"type": "solid-dot"
},
"on-show": {
"type": ""
},
"font-size": 15,
"loop": false,
"type": "line",
"tip": "#val#%"
}
]
In the above array example I need to add data to values array which is part of elements array dynamically. How do I do it using JavaScript push method?
As you will see, it's much easier to conceptualise your code if it is formatted well. Tools like jsBeautifier can help with this task.
First, it's clear that elements is part of a JS object. We'll call it foo, but you'll have to change this to the correct name in your code.
foo.elements[0].values.push({
value: 'some value'
});
This will add a new object to the values array.
elements[0].values.push({"value": new_value});
if the above is named var obj,
obj['elements'][0]['values'].push(someValue);
Presuming elements is part of an object called myObj for the example below, you could use either syntax.
myObj["elements"][0]["values"].push({ value: "my new value" });
or
myObj.elements[0].values.push({ value: "my new value" });

json - How to properly create json array

Im new to JSON and I have to deal with a complex one.
Please see image below:
It has an error:
I don't know how to properly separate the 2 json arrays. I even tried to use : instead of , on line 18 but I still get errors. BTW, I use http://jsonlint.com/ to validate.
On line 2 you gave a key, but failed to do so on line 19. You have to keep the structure.
Remove the key on line 2, they shouldn't be used for arrays in that way.
Edit: In addition, you are trying to put arrays right in objects, switch the opening and ending object marks ({}) with ([]) for arrays on your first and last line.
[
[
{...},
{...},
...
{...}
],
[
{...},
{...},
...
{...}
],
...
[
{...},
{...},
...
{...}
]
]
I believe the correct way to build this JSON should be:
{
"glEntries": [
{
"generalLedgerId":1,
"accountId": 34,
"amount" : 32334.23,
"descripction": "desc1",
"debit" : "Yes"
},
{
"generalLedgerId":2,
"accountId": 35,
"amount" : 323.23,
"descripction": "desc",
"debit" : "Yes"
},
...
]
}
There are many ways to construct JSON data, but it depends on your data and the way you want to present it. Here are a couple examples - hope it helps:
{
"glEntries": [
{
"object1-prop1": "one"
},
{
"object2-prop1": 1,
"object2-prop2": "two"
},
{
"object3-prop1": [
"a",
"r",
"r",
"a",
"y"
],
"object3-prop1.1": "string"
}
],
"otherEntries": [
{
"objectx": "x"
},
{
"objecty": "y"
},
{
"objectz": [
1,
2,
3,
4
]
}
],
"oneEntry": "json"
}
Other Example:
[
{
"obj1-prop": 222
},
{
"obj2-prop": "object2"
},
{
"obj3-prop": "Object3"
},
[
"a",
"r",
"r",
"a",
"y",
777,
888
],
"string",
178,
{
"objectProp": "testing123"
}
]
You have more {} than needed and will make parsing your JSON more difficult:
Structure will work a lot better like this:
{"glentries":[
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"}
]
}
Now glentries is an array of objects that have multiple properties to them.
alert( glentries[0].property2 )
The parent structure is an Object, so it is expecting a string Key for the second array. It it's supposed to be an array of arrays, you should be using an array and not an Object.

Categories