Find a key value based on a match in Javascript - javascript

I'm trying to return the uuid where the urns key has this match.
"urns": [
"whatsapp:27820111111"
],
What should be returned d7b9f88c-b359-4d69-926d-536c0d2892e0 since it has that phone number match. How can this be done programmatically.
Here's are the two dicts.
{
"next": "https://random.com=",
"previous": null,
"results": [
{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [
{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [
{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
]
}
I'm able to loop through and find the urn but I'm not sure how to step back to get the uuid.

Pass in the results array and the urn string to this function. If found it will return the uuid, else it will return null.
function getIdFromUrn(results, urn) {
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.urns.includes(urn)) {
return result.uuid; // urn found
}
}
return null; // not found
}
console.log(getIdFromUrn(results, 'whatsapp:27820111111'));

You don't need to loop when you can use find(...) to match against a value.
See demo below
var data = [{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
];
const lookingFor = "whatsapp:27820111111";
const foundIt = data.find(el => {
return (el.urns.indexOf(lookingFor) !== -1);
});
console.log(foundIt.uuid);

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]}`);
}

How to structure and all data in the objective from Json at App script

The JSON data I am working on it. This is coming from Facebook ad API. This is being build for google data studio connector
{
"data": [
{
"adcreatives": {
"data": [
{
"actor_id": "8834759718540",
"id": "538"
}
]
},
"insights": {
"data": [
{
"ad_id": "34536578578",
"impressions": "89108",
"actions": [
{
"action_type": "comment",
"value": "02"
},
{
"action_type": "post",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-10T22:59:33+0600",
"id": "34536578578"
},
{
"adcreatives": {
"data": [
{
"actor_id": "7834759718970",
"id": "342"
}
]
},
"insights": {
"data": [
{
"ad_id": "238509545896206",
"impressions": "57803",
"actions": [
{
"action_type": "post_engagement",
"value": "2102"
},
{
"action_type": "page_engagement",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-11T22:59:33+0600",
"id": "238509545896206"
}
],
"paging": {
"cursors": {
"before": "dfgdfgdfgdfsdgdfgdfgdfgdfgdgdg",
"after": "yuyuyuyutyuytuyutytynfrgersggsgs"
}
}
}
Here is the JavaScript code I have used in google app script but it is showing error. I know it is totally wrong
var data = {data: parseData.data.map(({actions, ...rest}) => ({...rest,...Object.fromEntries(actions.map(({action_type, value}) =>[action_type, value]))}))};
console.log(data);
Output should be like the following way so that I can get all the data in objective
{
"data": [
{
"actor_id": "8834759718540",
"id": "538",
"ad_id": "34536578578",
"impressions": "89108",
"comment": "02",
"post": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10",
"created_time": "2022-06-10T22:59:33+0600"
},
{
"actor_id": "7834759718970",
"id": "342",
"ad_id": "238512373324806",
"impressions": "57803",
"post_engagement": "2102",
"page_engagement": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
"created_time": "2022-06-11T22:59:33+0600"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MQZDZD"
}
}
}
You can try the code below, but it only works if adcreatives.data and insights.data have only 1 element :
let part = data.data.map(item => ({
"actor_id": item.adcreatives.data.at(0).actor_id,
"id": item.adcreatives.data.at(0).id,
"ad_id": item.insights.data.at(0).ad_id,
"impressions": item.insights.data.at(0).impressions,
"comment": item.insights.data.at(0).actions.at(0).value,
"post": item.insights.data.at(0).actions.at(1).value,
"date_start": item.insights.data.at(0).date_start,
"date_stop": item.insights.data.at(0).date_stop,
"created_time": item.created_time
}));
let result = {
data: part,
paging: data.paging
}
console.log(result);

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)

Remove some values of object from json

I have this json-
"SkuList": [
{
"active": null,
"id": 698027,
"productSKUName": "v1",
"productSKUDescription": null,
"productSKUId": "02ffea0f-3d05-44"
},
{
"active": null,
"id": 698028,
"productSKUName": "v2",
"productSKUDescription": null,
"productSKUId": "628acbb9-0bdb-4ccf"
},
]
How do I filter this json and return this -
"brandProductSkuList": [
{
"id": 698027,
"productSKUId": "02ffea0f-3d05-4436",
},
{
"id": 698028,
"productSKUId": "628acbb9-0bdb-4ccf"
},
]
I want to remove certain properties of the object. How do I do this?
Yo can use map for this:
var SkuList = [
{
"active": null,
"id": 698027,
"productSKUName": "v1",
"productSKUDescription": null,
"productSKUId": "02ffea0f-3d05-44"
},
{
"active": null,
"id": 698028,
"productSKUName": "v2",
"productSKUDescription": null,
"productSKUId": "628acbb9-0bdb-4ccf"
},
];
var brandProductSkuList = SkuList.map((sku) => ({
id: sku.id,
productSkuId: sku.productSKUId
}));
console.log(brandProductSkuList);
Like this
var newObj=SkuList.map(x=>({id:x.id,productSKUId:x.productSKUId}))
var input = {"SkuList": [
{
"active": null,
"id": 698027,
"productSKUName": "v1",
"productSKUDescription": null,
"productSKUId": "02ffea0f-3d05-44"
},
{
"active": null,
"id": 698028,
"productSKUName": "v2",
"productSKUDescription": null,
"productSKUId": "628acbb9-0bdb-4ccf"
},
]
};
var output = input["SkuList"].map( o => (
{"id" : o["id"],"productSKUId" : o["productSKUId"] }
));
var outputObject = {
"brandProductSkuList": output
}
console.log(outputObject);
Recreate the array with Array#map() function
var arr = {"SkuList": [{ "active": null, "id": 698027,"productSKUName": "v1", "productSKUDescription": null, "productSKUId": "02ffea0f-3d05-44"},{"active": null,"id": 698028, "productSKUName": "v2","productSKUDescription": null, "productSKUId": "628acbb9-0bdb-4ccf"},]}
var res = {'brandProductSkuList':arr.SkuList.map(function(a){
return ({id:a['id'],productSKUName: a['productSKUName'],})
})}
console.log(res)

Getting a variable from a multidimentional JSON array using Jquery

I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig
response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.
Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});
Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data

Categories

Resources