Remove extra layer from object - javascript

I have some web-hook which returns next data:
"data": {
"object": {
"id": "cus_JYmRConwwwbDjw",
"object": "customer",
"address": null,
"balance": 0,
"created": 1622105261,
"currency": null,
"default_source": null,
"delinquent": false,
"description": null,
"discount": null,
"email": null,
"invoice_prefix": "7BA9446D",
"invoice_settings": {
"custom_fields": null,
"default_payment_method": "pm_1Ivesgeee6awlUaOWjDDzmv",
"footer": null
},
"livemode": false,
"metadata": {},
"name": null,
"next_invoice_sequence": 1,
"phone": null,
"preferred_locales": [],
"shipping": null,
"sources": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_JYmRCewwea5bDjw/sources"
},
"subscriptions": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_JYmewenGa5bDjw/subscriptions"
},
"tax_exempt": "none",
"tax_ids": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_JYmRCowea5bDjw/tax_ids"
},
"tax_info": null,
"tax_info_verification": null
},
"previous_attributes": {
"invoice_settings": {
"default_payment_method": null
}
}
},
"type": "customer.updated"
}
To access for example id I need to use next path data.object.id.
How I can avoid using this not readable, not needed object item in path?
What I need is data.id

Related

Incorrect Maquest Direction Route API Feedback

I am integrating the MapQuest API Direction Routing function into my website. However, when I submit my request to the API, it returns incorrect routing points between 2 destinations.
Below is the request form I POST to the API: http://www.mapquestapi.com/directions/v2/route?key=[APIKEY]
{
"locations": [
{
"latLng": {
"lat": 37.47601247,
"lng": 126.96594338
}
},
{
"latLng": {
"lat": 37.4713402954355,
"lng": 126.95234849232048
}
}
],
"options": {
"avoids": [],
"avoidTimedConditions": false,
"doReverseGeocode": false,
"enhancedNarrative": true,
"generalize": 0,
"narrativeType": "text",
"routeType": "fastest",
"shapeFormat": "raw",
"unit": "k"
}
}
And the results that I received, I used the startPoint.lng and startPoint.lat in the maneuvers, but that doesn't seem to be correct
Below is the return results and map illustrations:
{
"route": {
"sessionId": "AHEA5gcAAFMBAAANAAAAMgAAAIQAAAB42mNoYWBgZGJgYGDPSC1KtUrOfcOaA-IybLykdYbrcqHnrSM-y6L8v3nd4t63PIoBC0DXeI7hyGImxx9ut9iLl0YdZPO69S5mBVaNILAwZvIzEA0AW5Egkyj61e4:car",
"realTime": 31,
"distance": 0.6,
"time": 31,
"formattedTime": "00:00:31",
"hasHighway": false,
"hasTollRoad": false,
"hasBridge": false,
"hasSeasonalClosure": false,
"hasTunnel": false,
"hasFerry": false,
"hasUnpaved": false,
"hasTimedRestriction": false,
"hasCountryCross": false,
"shape": {
"shapePoints": [
37.483936,
126.974279,
37.48681,
126.96995,
37.487346,
126.969139
],
"legIndexes": [
0,
3
],
"maneuverIndexes": [
0,
2
]
},
"legs": [
{
"index": 0,
"hasTollRoad": false,
"hasHighway": false,
"hasBridge": false,
"hasUnpaved": false,
"hasTunnel": false,
"hasSeasonalClosure": false,
"hasFerry": false,
"hasCountryCross": false,
"hasTimedRestriction": false,
"distance": 0.6,
"time": 31,
"formattedTime": "00:00:31",
"origIndex": 0,
"origNarrative": "",
"destIndex": 0,
"destNarrative": "",
"maneuvers": [
{
"index": 0,
"distance": 0.6,
"narrative": "Head northwest. Go for 591 m.",
"time": 31,
"direction": 2,
"directionName": "Northwest",
"signs": [],
"maneuverNotes": [],
"formattedTime": "00:00:31",
"transportMode": "car",
"startPoint": {
"lng": 126.974279,
"lat": 37.483936
},
"turnType": 0,
"mapUrl": "",
"attributes": 0,
"iconUrl": "",
"streets": []
},
{
"index": 1,
"distance": 0,
"narrative": "Arrive at your destination.",
"time": 0,
"direction": 0,
"directionName": "None",
"signs": [],
"maneuverNotes": [],
"formattedTime": "00:00:00",
"transportMode": "car",
"startPoint": {
"lng": 126.969139,
"lat": 37.487345999999995
},
"turnType": 0,
"mapUrl": "",
"attributes": 0,
"iconUrl": "",
"streets": []
}
]
}
],
"options": {
"avoids": [],
"avoidTimedConditions": false,
"doReverseGeocode": false,
"enhancedNarrative": true,
"generalize": 2,
"narrativeType": "text",
"routeType": "FASTEST",
"shapeFormat": "raw",
"unit": "K",
"walkingSpeed": -1,
"highwayEfficiency": 22,
"locale": "en_US",
"useTraffic": false,
"timeType": 0,
"dateType": 0,
"sideOfStreetDisplay": true
},
"boundingBox": {
"ul": {
"lng": 126.969139,
"lat": 37.487345999999995
},
"lr": {
"lng": 126.974279,
"lat": 37.483936
}
},
"routeWarnings": [],
"maxRoutes": "",
"locations": [
{
"street": "",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "",
"adminArea5Type": "City",
"adminArea4": "",
"adminArea4Type": "County",
"adminArea3": "",
"adminArea3Type": "State",
"adminArea1": "",
"adminArea1Type": "Country",
"postalCode": "",
"geocodeQualityCode": "XXXXX",
"geocodeQuality": "LATLNG",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 37.47601247,
"lng": 126.96594338
},
"displayLatLng": {
"lat": 37.47601247,
"lng": 126.96594338
}
},
{
"street": "",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "",
"adminArea5Type": "City",
"adminArea4": "",
"adminArea4Type": "County",
"adminArea3": "",
"adminArea3Type": "State",
"adminArea1": "",
"adminArea1Type": "Country",
"postalCode": "",
"geocodeQualityCode": "XXXXX",
"geocodeQuality": "LATLNG",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 37.4713402954355,
"lng": 126.95234849232048
},
"displayLatLng": {
"lat": 37.4713402954355,
"lng": 126.95234849232048
}
}
],
"locationSequence": [
0,
1
]
},
"info": {
"statuscode": 0,
"copyright": {
"text": "© 2022 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText": "© 2022 MapQuest, Inc."
},
"messages": []
}
}
Are there any parameters I have to adjust to archive the correct information? I have tried to change generalize parameter but it does not help much. I used to get the location really precise about a month ago... This is strange to me
MapQuest's map/route data in South Korea is lacking a lot of detail. We hope some day to have more detailed routing in the area.

How do I group an array of objects by a singular array property embedded within a property of that array

I have an array of objects that comes in from an api. The data is in this format:
[
{
"__typename": "directus_fields",
"field": "heading",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "hero",
"validation_message": null,
"id": 37,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "introduction",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "about_us",
"validation_message": null,
"id": 38,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_title",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 41,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_duration",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 42,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_text",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 43,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_image",
"type": "uuid",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 36,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 44,
"required": false,
"validation": null,
"interface": "file-image",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "philosophy_title",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "philosophy",
"validation_message": null,
"id": 45,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "philosophy_text",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "philosophy",
"validation_message": null,
"id": 46,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "title",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "about_us",
"validation_message": null,
"id": 52,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "hero_text",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "hero",
"validation_message": null,
"id": 164,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
}
]
I would like to group the data in the array by the meta group name. All meta group names that are similar should be in a new array object.
I tried this but I couldnt get it to work
const tree = [];
const children = {};
data.forEach((item) => {
const newItem = { ...item } as ParsedMenuItem;
const { id: newItem?.meta?.group, parentId: parentId = 0 } = newItem;
children[id] = children[id] || [];
newItem.childMenu = children[id];
parentId
? (children[parentId] = children[parentId] || []).push(newItem)
: tree.push(newItem);
});
return tree;
I just want all similar meta group name to be under one object. I have no idea on how to go about this due to the nested structure.
You could group your data by meta.group using Array.reduce(). Here is an example:
result = data.reduce((a, i) => {
a[i.meta.group] = a[i.meta.group] || [];
a[i.meta.group].push(i);
return a;
}, {});
console.log(result)
<script>
let data = [{
"__typename": "directus_fields",
"field": "heading",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "hero",
"validation_message": null,
"id": 37,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "introduction",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "about_us",
"validation_message": null,
"id": 38,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_title",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 41,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_duration",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 42,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_text",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 43,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "campaign_image",
"type": "uuid",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 36,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "campaign",
"validation_message": null,
"id": 44,
"required": false,
"validation": null,
"interface": "file-image",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "philosophy_title",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "philosophy",
"validation_message": null,
"id": 45,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "philosophy_text",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "philosophy",
"validation_message": null,
"id": 46,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "title",
"type": "string",
"schema": {
"__typename": "directus_fields_schema",
"max_length": 255,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "about_us",
"validation_message": null,
"id": 52,
"required": false,
"validation": null,
"interface": "input",
"hidden": false
}
},
{
"__typename": "directus_fields",
"field": "hero_text",
"type": "text",
"schema": {
"__typename": "directus_fields_schema",
"max_length": null,
"is_unique": false,
"is_nullable": true
},
"meta": {
"__typename": "directus_fields_meta",
"group": "hero",
"validation_message": null,
"id": 164,
"required": false,
"validation": null,
"interface": "input-rich-text-html",
"hidden": false
}
}
]
</script>

Stripe invoice.upcoming webhook

I want to know what is the example data from invoice.upcoming webhook of stripe.
Is the data.object.id is null?
Where I can get the amount? Is it on the data.object.amount_paid or data.object.amount_due?
And what is the status of this invoice?
Example data I got here in stackoverflow but I think it's not complete?
{
"created": 1326853478,
"livemode": false,
"id": "evt_000000000010000",
"type": "invoice.upcoming",
"object": "event",
"request": null,
"pending_webhooks": 1,
"api_version": "2017-06-05",
"data": {
"object": {
"id": null,
"object": "invoice",
"amount_due": 0,
"amount_paid": 0,
"application_fee": null,
"attempt_count": 0,
"attempted": true,
"charge": null,
"closed": true,
"currency": "usd",
"customer": "cus_J1QXR23OrUTxx1fk",
"date": 1503541536,
"description": null,
"discount": null,
"ending_balance": 0,
"forgiven": false,
"lines": {
"data": [
{
"id": "sub_BNx15yNiTkAlQOye",
"object": "line_item",
"amount": 500,
"currency": "jpy",
"description": null,
"discountable": true,
"livemode": true,
"metadata": {
},
"period": {
"start": 1507604796,
"end": 1510283196
},
"plan": {
"id": "bplan",
"object": "plan",
"amount": 500,
"created": 1504352393,
"currency": "jpy",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"name": "B plan",
"statement_descriptor": null,
"trial_period_days": null
},
"proration": false,
"quantity": 1,
"subscription": null,
"subscription_item": "si_1B0LmKE9P3qCpf5erqbpMxkI",
"type": "subscription"
}
],
"total_count": 1,
"object": "list",
"url": "/v1/invoices/in_1AuB2KE9P3qCpf5ekFh7qpAi/lines"
},
"livemode": false,
"metadata": {
},
"next_payment_attempt": null,
"paid": true,
"period_end": 1503541536,
"period_start": 1503541536,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"subscription": "sub2JQx1xlg9zIFhk",
"subtotal": 0,
"tax": null,
"tax_percent": null,
"total": 0,
"webhooks_delivered_at": 1503541537
}
}
}
Those Events generated from the Dashboard are totally fake, so I don't think you'll ever find usable data in them, but amount_due is what you want here.
Since Upcoming Invoices haven't been created yet - they're just a preview of future charges - they have no ID or status.
Here's a full example of Stripe's invoice.upcoming event.
I found it using the test clocks feature. Please note that is the kind of data you'll get by renewing a yearly susbscription.
{
"object": "invoice",
"account_country": "US",
"account_name": "Your company",
"account_tax_ids": null,
"amount_due": 9900,
"amount_paid": 0,
"amount_remaining": 9900,
"application_fee_amount": null,
"attempt_count": 0,
"attempted": false,
"automatic_tax": {
"enabled": false,
"status": null
},
"billing_reason": "upcoming",
"charge": null,
"collection_method": "charge_automatically",
"created": 1679397051,
"currency": "usd",
"custom_fields": null,
"customer": "cus_XXXXXXXX",
"customer_address": null,
"customer_email": "xxxx#user.io",
"customer_name": "Customer name",
"customer_phone": null,
"customer_shipping": null,
"customer_tax_exempt": "none",
"customer_tax_ids": [],
"default_payment_method": null,
"default_source": null,
"default_tax_rates": [],
"description": null,
"discount": null,
"discounts": [],
"due_date": null,
"ending_balance": 0,
"footer": null,
"last_finalization_error": null,
"lines": {
"object": "list",
"data": [
{
"id": "il_tmp_xxxxxxxxxxxxxxxxxxxxxxx",
"object": "line_item",
"amount": 9900,
"currency": "usd",
"description": "1 × Your sub (at $99.00 / year)",
"discount_amounts": [],
"discountable": true,
"discounts": [],
"livemode": false,
"metadata": {},
"period": {
"end": 1711019451,
"start": 1679397051
},
"plan": {
"id": "price_XXXXXXXXXXXXXXXX",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 9900,
"amount_decimal": "9900",
"billing_scheme": "per_unit",
"created": 1600678675,
"currency": "usd",
"interval": "year",
"interval_count": 1,
"livemode": false,
"metadata": {},
"nickname": null,
"product": "prod_XXXXXXXXXXXX",
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"price": {
"id": "price_XXXXXXXXXXXXXX",
"object": "price",
"active": true,
"billing_scheme": "per_unit",
"created": 1600678675,
"currency": "usd",
"livemode": false,
"lookup_key": null,
"metadata": {},
"nickname": null,
"product": "prod_XXXXXXXXXXXX",
"recurring": {
"aggregate_usage": null,
"interval": "year",
"interval_count": 1,
"trial_period_days": null,
"usage_type": "licensed"
},
"tax_behavior": "unspecified",
"tiers_mode": null,
"transform_quantity": null,
"type": "recurring",
"unit_amount": 9900,
"unit_amount_decimal": "9900"
},
"proration": false,
"proration_details": {
"credited_items": null
},
"quantity": 1,
"subscription": "sub_XXXXXXXXXXXXXX",
"subscription_item": "si_XXXXXXXXXXXX",
"tax_amounts": [],
"tax_rates": [],
"type": "subscription"
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/invoices/upcoming/lines?customer=cus_XXXXXXXXXXXX&subscription=sub_XXXXXXXXXXX"
},
"livemode": false,
"metadata": {},
"next_payment_attempt": 1679400651,
"number": null,
"on_behalf_of": null,
"paid": false,
"paid_out_of_band": false,
"payment_intent": null,
"payment_settings": {
"payment_method_options": null,
"payment_method_types": null
},
"period_end": 1679397051,
"period_start": 1647861051,
"post_payment_credit_notes_amount": 0,
"pre_payment_credit_notes_amount": 0,
"quote": null,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"status": "draft",
"status_transitions": {
"finalized_at": null,
"marked_uncollectible_at": null,
"paid_at": null,
"voided_at": null
},
"subscription": "sub_XXXXXXXXXXXX",
"subtotal": 9900,
"tax": null,
"test_clock": "clock_1Kfj8pAP8XE2C2mat1YQW7Rg",
"total": 9900,
"total_discount_amounts": [],
"total_tax_amounts": [],
"transfer_data": null,
"webhooks_delivered_at": null
}

Angular track by object.id

I have following JSON data received form REST api.
[
{
"names": {
"en": "test123"
},
"children": [],
"id": "68d87e8c-42f5-4f11-b25a-b30624246c3b",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test123",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
},
{
"names": {
"en": "test456"
},
"children": [],
"id": "d175e6d1-874e-4909-afb2-790c0a940c3f",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test456",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
}
]
I'm trying to display it using directive ng-repeat. Using track by object.id.
It is used like this:
<tr ng-repeat="chapter in chapters | filter: search track by chapter.id">
But the problem is that the ngRepeat:Dupes error still appear. I have checked the data contained in JSON, but there is no duplicite id in it. Do you know why the ngRepeat:Dupes error persists?
Based on the data given, no duplicate error is thrown, below is jsfiddle.
<div ng-controller="MainCtrl">
<input type="text" ng-model="search">
<div ng-repeat="chapter in chapters | filter: search track by chapter.id">{{chapter.id}}</div>
</div>
controller
$scope.chapters = [{
"names": {
"en": "test123"
},
"children": [],
"id": "68d87e8c-42f5-4f11-b25a-b30624246c3b",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test123",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
}, {
"names": {
"en": "test456"
},
"children": [],
"id": "d175e6d1-874e-4909-afb2-790c0a940c3f",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test456",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
}]
http://jsfiddle.net/75sdsuz2/2/

how do I fetch the second level array values in JSON data using jQuery each()

I would like to select a particular value using jquery each from the second and third level array. This is my JSON response looks like:
{
"events": [{
"id": 847843,
"name": "Strasbourg IG at Limoges CSP",
"timezone": "GMT",
"timezoneOffset": 0,
"time": 1401983400000,
"timeUtc": "2014-06-05T18:50:00+00:00",
"status": "live",
"wpRef": "847843",
"parentCategoryId": 22,
"parentCategoryName": "Basketball",
"categoryId": 7443,
"categoryName": "French Championnat Pro A ",
"racingEvent": null,
"raceNumber": null,
"marketCount": 3,
"prefix": null,
"nameSeparator": null,
"markets": [{
"id": 4943131,
"primitiveType": 2,
"primitiveName": "Head to Head",
"typeId": 36,
"name": "Head to Head",
"marketDescription": "Select the winner of the match.",
"marketRules": "Includes extra time.\r",
"eventNotices": null,
"autoHide": false,
"status": "live",
"bettingStatus": "enabled",
"period": "Fulltime",
"allowMultiple": true,
"betInRunTime": 0,
"track": null,
"weather": null,
"betTypes": [{
"id": 1,
"name": "Win",
"finishingOrder": null,
"products": []
}],
"selections": [{
"id": 288481048,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Strasbourg IG",
"prefix": "",
"mpId": 288481048,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 2.6,
"usPrice": "+160",
"value": 2.60
}]
}, {
"id": 288481039,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Limoges CSP",
"prefix": "",
"mpId": 288481039,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.44,
"usPrice": "-227",
"value": 1.44
}]
}]
}, {
"id": 4943134,
"primitiveType": 99,
"primitiveName": "Other",
"typeId": 1266,
"name": "Odd or Even Total",
"marketDescription": "Select whether the amount of points scored in the match will be an odd or even number (zero = even)\r\rIncludes overtime.",
"marketRules": "For this market zero will be deemed to be an even number.\r\rNo bonus bets.\r\rIncludes overtime.",
"eventNotices": null,
"autoHide": true,
"status": "live",
"bettingStatus": "enabled",
"period": "Fulltime",
"allowMultiple": true,
"betInRunTime": 0,
"track": null,
"weather": null,
"betTypes": [{
"id": 1,
"name": "Win",
"finishingOrder": null,
"products": []
}],
"selections": [{
"id": 288481066,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Even",
"prefix": "",
"mpId": 288481066,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.85,
"usPrice": "-118",
"value": 1.85
}]
}, {
"id": 288481075,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Odd",
"prefix": "",
"mpId": 288481075,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.85,
"usPrice": "-118",
"value": 1.85
}]
}]
}, {
"id": 4943137,
"primitiveType": 99,
"primitiveName": "Other",
"typeId": 1298,
"name": "Match Result",
"marketDescription": null,
"marketRules": null,
"eventNotices": null,
"autoHide": false,
"status": "live",
"bettingStatus": "enabled",
"period": "Fulltime",
"allowMultiple": true,
"betInRunTime": 0,
"track": null,
"weather": null,
"betTypes": [{
"id": 1,
"name": "Win",
"finishingOrder": null,
"products": []
}],
"selections": [{
"id": 288481102,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Strasbourg IG",
"prefix": "",
"mpId": 288481102,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 2.63,
"usPrice": "+163",
"value": 2.63
}]
}, {
"id": 288481084,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Limoges CSP",
"prefix": "",
"mpId": 288481084,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.5,
"usPrice": "-200",
"value": 1.50
}]
}, {
"id": 288481093,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Draw",
"prefix": "",
"mpId": 288481093,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 13.00,
"usPrice": "+1200",
"value": 13.00
}]
}]
}],
"result": null
}]
}
I am able to fetch all the "name" field from events category using the below code.
drawAllEvents: function (events) {
var $container = $('#someID ul');
$.each(events, function(i, event) {
$('<a />', { text: event.name, href: '#' }).wrap('<li />').parent().appendTo($container);
});
}
Now I am trying to fetch "primitiveName" field from the markets array using another function but for some reason it returns undefined. Here is my code
drawAllBetTypesFilter: function (events)  {
$('#bettype-sport ul').empty();
var betTypeFilter = $('#bettype-sport ul');
$.each(events, function (i, event) {
$.each(event.markets, function (market) {
var betTypeName = market.primitiveName;
$('<a />', {
text: betTypeName
}).wrap('<li />').parent().appendTo(betTypeFilter);
});
});
}
Furthermore, How do I fetch third level array, for e.g If I want to fetch all "name" fields under "betTypes" which is a child of "markets" object.
EDIT: 1 - Also mentioned in my comment. How do I group similar primitiveName values together in my list instead of displaying them seperately.
Here is the fiddle to show how am I fetching values in first level. FIDDLE LINK
The first parameter passed to the each() iteration function is the index of the current element in the array, so in your current code your market parameter is not the element from the array but instead an int. Try this:
var betTypeFilter = $('#bettype-sport ul');
$.each(events, function (i, event) {
$.each(event.markets, function (i, market) { // <- note 'i' first param
var betTypeName = market.primitiveName;
$('<a />', {
text: betTypeName
}).wrap('<li />').parent().appendTo(betTypeFilter);
// to get betTypes for this market:
$.each(market.betTypes, function(i, betType) {
// do something...
console.log(betType);
});
});
});
To fetch the name under betTypes would take another loop. Or, if there is only ever one object in the array you could hard-code access to the first element only:
market.betTypes[0].name; // == 'Win'
Alternatively, instead of using the jquery each function, why not just use traditional javascript looping. The $.each method isn't nearly as efficient as that.
drawAllBetTypesFilter: function (events) {
$('#bettype-sport ul').empty();
var betTypeFilter = $('#bettype-sport ul');
for(var i = 0; i < events.length; i++) {
var event = events[i];
for(var j = 0; j < event.markets.length; j++) {
var market = event.markets[j];
var betTypeName = market.primitiveName;
$('<a />', {
text: betTypeName
}).wrap('<li />').parent().appendTo(betTypeFilter);
};
};
}

Categories

Resources