best way to loop over Json in Javascript - javascript

SO I have this setting json
[{
"name": "Business",
"skip": "0",
"pos": "1"
},
{
"name": "contact",
"skip": "1",
"pos": "3"
},
{
"name": "UKSite",
"skip": "0",
"pos": "2"
}
]
Then I have my data json
[{
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Sri",
"con_fName": "Jhon",
"con_lName": "Snow",
"emails": ["maheshwar#hsjsk.com", ""],
"phones": ["8867116216", ""]
},
"repeatable": false
}, {
"name": "UKAddress",
"hideShow": true,
"data": {
"addAddress": [{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}, {
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}]
},
"repeatable": false
}, {
"name": "Business",
"hideShow": true,
"data": {
"biss_name": "Nano Corporation"
},
"repeatable": false
}, {
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Mr",
"con_fName": "Roshan",
"con_lName": "Aslam",
"emails": ["roshan#throughbit.com"],
"phones": ["8867116216"]
},
"repeatable": true
}, {
"name": "UKSite",
"hideShow": true,
"data": {
"site_name": "naonocrporation.co.uk",
"external_rff": "fsfsfs",
"con_title": "Mr",
"con_fName": "Kash",
"con_lName": "Sangh",
"emails": ["kash#youremail.com"],
"phones": ["8867116216"],
"addAddress": [{
"add_bilding_num": "",
"add_street_name": "",
"add_town": "",
"add_county": "",
"add_pc": "",
"add_type": ""
}],
"ElecMeter": [{
"distrib_id": "DISTRIBUTOR ID",
"pc": "PROFILE CLASS",
"mtc": "METER TIMESWITCH CODE",
"llf": "LINE LOSS FACTOR",
"mpc": "MPAN CORE",
"eac": "EAC",
"c_supplr": "CURRENT SUPPLIER",
"c_date": "CURRENT END DATE",
"select": true
}, {
"distrib_id": "",
"pc": "",
"mtc": "",
"llf": "",
"mpc": "",
"eac": "",
"c_supplr": "",
"c_date": ""
}],
"GasMeter": [{
"mprn": "MPRN",
"aq": "AQ",
"g_c_supplr": "CURRENT SUPPLIER",
"g_c_date": "CURRENT END DATE"
}]
},
"repeatable": true
}]
I have to loop on the data json and using the information from setting json need to create a new Json
for example
my new json should look like this
[{
"name": "Business",
"hideShow": true,
"data": {
"biss_name": "Nano Corporation"
},
"repeatable": false
},
{
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Mr",
"con_fName": "Roshan",
"con_lName": "Aslam",
"emails": [
"roshan#throughbit.com"
],
"phones": [
"8867116216"
]
},
"repeatable": true
},
{
"name": "UKAddress",
"hideShow": true,
"data": {
"addAddress": [{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
},
{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}
]
},
"repeatable": false
}
]
You can Observe , The term skip:1 which means skip the first one and add rest also the terminology pos:1 which is telling what should be the position of the object in the new array.
Any help would be great
Update 1
I came up with this snippet
ar finalArray = []
for(var i = 0; i < b.length; i++){
var counter = 0;
for(var j = 0; j < a.length; j++){
if(b[i].name == a[j].name){
if(counter < b[i].skip){
counter++;
continue;
}
finalArray.push(a[j])
}
}
}
Thanks

As you are dealing with an array of objects and you want to modify each one during the iteration based on conditions, I'd recommend you to use forEach
You have docs and examples here:
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/map

Related

How to Parse nested Json In Java script

I have this json in js,
and i am trying to get the key from the "Data" Object, like the SessionId and Email.
Please Help...
{
"HasError": false,
"Errors": [],
"ObjectName": "WebCheckoutCreateSessionResponse",
"Data": {
"HasError": false,
"ReturnCode": 0,
"ReturnMessage": null,
"SessionId": "abcde",
"SessionUrl": "https://pci.aaa.com/WebCheckout/Angular/Checkout.html#!/ZCreditWebCheckout/55cf7d1306b2bcc15d791dde524d2b4f616421172e6d75a013597c8dd2668843",
"RequestData": {
"Key": "ad",
"Local": "He",
"UniqueId": "<InvNo>1705</InvNo><InvYear>3102</InvYear><SugMismah>15</SugMismah><key>ad</key>",
"SuccessUrl": "",
"CancelUrl": "",
"CallbackUrl": "",
"PaymentType": "regular",
"CreateInvoice": false,
"AdditionalText": "",
"ShowCart": true,
"ThemeColor": "005ebb",
"Installments": {
"Type": "regular",
"MinQuantity": 1,
"MaxQuantity": 12
},
"Customer": {
"Email": "someone#gmail.com",
"Name": "Demo Client",
"PhoneNumber": "077-3233190",
"Attributes": {
"HolderId": "none",
"Name": "required",
"PhoneNumber": "required",
"Email": "optional"
}
},
"CartItems": [
{
"Amount": 117,
"Currency": "US",
"Name": "Danny ",
"Description": "Hi ",
"Quantity": 1,
"Image": "https://www.aaa.com/site/wp-content/themes/z-credit/img/decisions/decision2.png",
"IsTaxFree": false
}
],
"GetCurrencyCode": "376",
"BitButtonEnabled": true,
"MaxPayButtonEnabled": true,
"ApplePayButtonEnabled": true,
"GooglePayButtonEnabled": true,
"ShowTotalSumInPayButton": true
}
},
"ResponseType": 0
}
const population = JSON.parse(xhr.responseText);
for (const key in population) {
if (population.hasOwnProperty(key)) {
console.log(`${key}: ${population[key]}`);
}
}
You forgot to index the Data property.
const population = JSON.parse(xhr.responseText).Data;
for (const key in population) {
console.log(`${key}: ${population[key]}`);
}

Need to get Name, Node Name and Phase Values from API

I am trying to get Name, Node Name and Phase values from JSON Data using JavaScript. Here is my JavaScript
<script>
$(document).ready(function () {
$.getJSON('http://ec2-3-82-117-70.compute-1.amazonaws.com:8080/api/v0/retrievePodStatus/default',
function (data) {
console.log(data)
document.body.append("Name: " + data.items[1].metadata.name);
// document.body.append(data.items[1].metadata.name);
// document.body.append(data.items[0].spec.nodeName);
});
});
</script>
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}
],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [
{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}
],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
},
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
Thanks, Much Appreciated
You were close with the code you posted. You just needed items[0] instead of items[1]. Remember the first element of an array is always 0. Other than that its as easy as checking the open and close brackets [] or {} to see where each nested object/array starts and ends.
Code:
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
snippet:
var data = {
"apiVersion": "v1",
"items": [{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}]
}],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}]
},
"status": {
"conditions": [{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
}],
}
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
console.log(name)
console.log(nodeName)
console.log(phase)

How to insert values of matching JSON Keys between 2 JSON files

I have 2 JSON files:
A Template JSON
A JSON output (from awscli)
The template is a small JSON file as below:
{
"DryRun": true,
"ImageId": "",
"KeyName": "",
"SecurityGroups": [
""
],
"InstanceType": "",
"Monitoring": {
"Enabled": false
},
"SubnetId": "",
"DisableApiTermination": true,
"PrivateIpAddress": "",
"IamInstanceProfile": {
"Arn": "",
"Name": ""
},
"EbsOptimized": true,
"TagSpecifications": [{
"ResourceType": "",
"Tags": [{
"Key": "",
"Value": ""
}]
}]
}
The original file is the output of aws ec2 describe-instances:
{
"Reservations": [{
"OwnerId": "123456789012",
"ReservationId": "r-12345678",
"Groups": [],
"Instances": [{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"RootDeviceType": "ebs",
"State": {
"Code": 16,
"Name": "running"
},
"EbsOptimized": false,
"LaunchTime": "2016-02-09T03:06:21.000Z",
"PublicIpAddress": "12.34.56.78",
"PrivateIpAddress": "172.31.1.2",
"ProductCodes": [],
"VpcId": "vpc-1a2b3c4d",
"StateTransitionReason": "",
"InstanceId": "i-abcd1234",
"ImageId": "ami-1234abcd",
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"KeyName": "tempKey",
"SecurityGroups": [{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYY"
}
],
"ClientToken": "NutKc123456789012",
"SubnetId": "subnet-00001234",
"InstanceType": "t2.medium",
"NetworkInterfaces": [{
"Status": "in-use",
"MacAddress": "02:AA:BB:CC:DD:EE",
"SourceDestCheck": true,
"VpcId": "vpc-1a2b3c4d",
"Description": "",
"Association": {
"PublicIp": "12.34.56.78",
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"IpOwnerId": "123456789012"
},
"NetworkInterfaceId": "eni-XXXXXXXX",
"PrivateIpAddresses": [{
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"Association": {
"PublicIp": "1.2.3.4",
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"IpOwnerId": "123456789012"
},
"Primary": true,
"PrivateIpAddress": "172.31.1.2"
}],
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"Attachment": {
"Status": "attached",
"DeviceIndex": 0,
"DeleteOnTermination": true,
"AttachmentId": "eni-attach-XXXXXXXX",
"AttachTime": "2016-01-13T08:33:37.000Z"
},
"Groups": [{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYYY"
}
],
"Ipv6Addresses": [],
"SubnetId": "subnet-00001234",
"OwnerId": "123456789012",
"PrivateIpAddress": "172.31.1.2"
}],
"SourceDestCheck": true,
"Placement": {
"Tenancy": "default",
"GroupName": "",
"AvailabilityZone": "ap-southeast-1b"
},
"Hypervisor": "xen",
"BlockDeviceMappings": [{
"DeviceName": "/dev/xvda",
"Ebs": {
"Status": "attached",
"DeleteOnTermination": true,
"VolumeId": "vol-33221100",
"AttachTime": "2016-01-13T08:33:39.000Z"
}
}],
"Architecture": "x86_64",
"StateReason": {
"Message": "Client.UserInitiatedShutdown: User initiated shutdown",
"Code": "Client.UserInitiatedShutdown"
},
"RootDeviceName": "/dev/xvda",
"VirtualizationType": "hvm",
"Tags": [{
"Value": "SomeValue",
"Key": "SomeKey"
},
{
"Value": "AnotherValue",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}]
}]
}
I want to copy the values of the Keys in the original JSON file to the template file.
For example, KeyName is a common key between the 2 JSON files. The corresponding value tempKey is replaced in the template file.
The main use case of this is: I am trying to migrate a number of servers on AWS from 1 region to another. This is a part of migration process which will remove tons of manual clicking and configuration on AWS Console.
Note: I use BASH command line.
There's a way to do this with jq but it doesn't take a JSON template as input.
You'll have to modify it to become a query. This isn't the actual query you need, but something to get you started:
cat temp.json | jq '.Reservations[].Instances[] | { DryRun, ImageId, KeyName, SecurityGroups, InstanceType, Monitoring }'
Where temp.json is your output above that I placed into a file. For regular commands, just do something like aws ec2 describe-instances | jq ...
The output that gives me (keep in mind the restricted set I queried for) is:
{
"DryRun": null,
"ImageId": "ami-1234abcd",
"KeyName": "tempKey",
"SecurityGroups": [
{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYY"
}
],
"InstanceType": "t2.medium",
"Monitoring": {
"State": "disabled"
}
}
Hope this helps.

Parse JSON with multiple levels

I am trying to parse this JSON that I have assigned to a javascript variable but I am having a hard time looping through it due to it having multiple levels
<script type="text/javascript">
var varJson = {
"d": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"type": "AlfWebApiInfrastructure.Poco.Office"
},
"Agency": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Agency"
}
},
"Advertiser": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Advertiser"
}
},
"Contacts": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 59980,
"jobId": 1000105450,
"mask": 67108863,
"name": "Name",
"jobtitle": "Job Title",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
},
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 64085,
"jobId": 1000105448,
"mask": 67108863,
"name": "name",
"jobtitle": "jobtitle",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
}
]
},
"id": 100013449,
"companyId": 1787,
"addressLine1": "addressLine1",
"addressLine2": "",
"addressLine3": "",
"addressLine4": "",
"addressLine5": "addressLine5",
"postCode": "postCode",
"regionId": "regionId",
"countyId": "countyId",
"tvAreaId": "L",
"telephone": "telephone",
"fax": "fax8",
"countryId": "countryId",
"email": "email",
"isdn": null,
"mask": 66060287
}
]
}
};
$(document).ready(function () {
//var parsed = JSON.parse(varJson);
alert(varJson);
});
</script>
I tried using this:
$.each(varJson, function (index, item) {
alert(item);
});
But it just says object in my alert.
try this,
function traverse(jsonObj) {
if( typeof jsonObj == "object" ) {
$.each(jsonObj, function(k,v) {
traverse(v);
});
}
else {
alert(jsonObj);
}
}
$(document).ready(function () {
traverse(varJson);
});
http://jsfiddle.net/satpalsingh/hXEr8/
with reference of Traverse all the Nodes of a JSON Object Tree with JavaScript
You don't need to parse it in your example.
Use console.log instead of alert and you will the the object in your web inspector.
If you do want to alert do something like this
alert(varJson.d.results[0].__metadata.id)

metadata configuration of fields in ExtJS DirectStore

I am trying to load grid data from a ExtDirect router. The results contain a metaData object that should reconfigure the store's fields. I am getting the following error however when I try to load my data:
Uncaught TypeError: Cannot read property 'sortType' of undefined (ext-all-debug.js:23943)
The JSON result is:
{
"action": "Dashboard",
"method": "dashboarddata",
"type": "rpc",
"result": {
"success": true,
"metaData": {
"sortInfo": {
"direction": "ASC",
"field": "id"
},
"fields": [{
"mapping": "id",
"id": "id"
},
{
"mapping": "owner",
"id": "owner"
},
{
"mapping": "name",
"id": "name"
},
{
"mapping": "type",
"id": "type"
},
{
"mapping": "strategy",
"id": "strategy"
},
{
"mapping": "primebroker",
"id": "primebroker"
},
{
"mapping": "startdate",
"id": "startdate"
},
{
"mapping": "date_afc_prelim_approval",
"id": "date_afc_prelim_approval"
},
{
"mapping": "date_afc_approval",
"id": "date_afc_approval"
},
{
"mapping": "date_submit_regulator",
"id": "date_submit_regulator"
},
{
"mapping": "date_approval_regulator",
"id": "date_approval_regulator"
},
{
"mapping": "enddate",
"id": "enddate"
},
{
"mapping": "main_iso_currency",
"id": "main_iso_currency"
},
{
"mapping": "nav_frequency",
"id": "nav_frequency"
},
{
"mapping": "date_first_nav",
"id": "date_first_nav"
},
{
"mapping": "launch_size",
"id": "launch_size"
},
{
"mapping": "target_size",
"id": "target_size"
},
{
"mapping": "memo",
"id": "memo"
},
{
"mapping": "isin_codes",
"id": "isin_codes"
},
{
"mapping": "status",
"id": "status"
}],
"totalProperty": "total",
"successProperty": "success",
"idProperty": "id",
"root": "data"
},
"data": [{
"status": "Project closed",
"strategy": "Strategy X",
"date_afc_approval": "2010-01-01",
"startdate": "2010-01-01",
"nav_frequency": "Bi-monthly",
"date_first_nav": "2010-01-01",
"enddate": "2010-01-01",
"date_approval_regulator": "2010-01-01",
"id": "1",
"date_afc_prelim_approval": "2010-01-01",
"isin_codes": "123",
"target_size": "2000",
"owner": "Some name",
"name": "First project",
"memo": "TEXTEXTEXT",
"main_iso_currency": "TND",
"primebroker": "Yes",
"date_submit_regulator": "2010-01-01",
"launch_size": "1000",
"type": "TypeX"
}],
"total": 1
},
"tid": 6
}
The store itself is configured like:
var store = new Ext.data.DirectStore({
idProperty: 'id'
,paramsAsHash: true
,directFn: MyApp.Direct.Dashboard.dashboarddata
,root:'data'
,autoLoad: false
,totalProperty:'total'
,fields: [
{name: 'id', mapping: 'id'},
{name: 'type', mapping: 'type'}
]
,baseParams: {
type: this.type,
filters: this.filters
}
});
Can anyone please help me? This is driving me nuts, I cannot see what I am doing wrong.
Thanks!
Rob
PS. I am using ExtJS 3.3.0
Why not debug that place using Chrome or Firefox debug facility? The helpful options is setting the break on exception in the Chrome.
I fixed it. Debugging did the trick.
Apparently when updating the fields through the metaData object in the JSON response you need to name the fields. ExtJS uses the name field as a lookup field internally. Strange thing is that with static configuration of a store's fields you don't need that field...
...
"fields": [{
"mapping": "id",
"name": "id",
"id": "id"
},
{
"mapping": "owner",
"name": "owner",
"id": "owner"
},
...

Categories

Resources