In a project I pull JSON-objects out of the Zammad-API.
I get the ticket:
[
{
"id": 53,
"group_id": 2,
"priority_id": 2,
"state_id": 2,
"organization_id": null,
"number": "740534",
"title": "Testanfrage Weichinger",
"owner_id": 3,
"customer_id": 3,
"note": null,
"first_response_at": "2022-11-15T07:19:04.078Z",
"first_response_escalation_at": null,
"first_response_in_min": 0,
"first_response_diff_in_min": 4320,
"close_at": null,
"close_escalation_at": null,
"close_in_min": null,
"close_diff_in_min": null,
"update_escalation_at": null,
"update_in_min": null,
"update_diff_in_min": null,
"last_contact_at": "2022-11-15T07:20:05.013Z",
"last_contact_agent_at": "2022-11-15T07:19:41.008Z",
"last_contact_customer_at": "2022-11-15T07:20:05.013Z",
"last_owner_update_at": "2022-11-15T12:08:48.875Z",
"create_article_type_id": 1,
"create_article_sender_id": 1,
"article_count": 3,
"escalation_at": null,
"pending_time": null,
"type": null,
"time_unit": null,
"preferences": {
"channel_id": 3,
"escalation_calculation": {
"first_response_at": "2022-11-15T07:19:04.078Z",
"last_update_at": "2022-11-15T07:20:05.013Z",
"last_contact_at": "2022-11-15T07:20:05.013Z",
"sla_id": 2,
"sla_updated_at": "2023-01-11T16:02:47.791Z",
"calendar_id": 2,
"calendar_updated_at": "2023-01-15T13:20:30.043Z",
"escalation_disabled": false
}
},
"updated_by_id": 3,
"created_by_id": 3,
"created_at": "2022-11-15T07:19:04.022Z",
"updated_at": "2023-01-16T07:40:29.206Z",
"last_close_at": null
}
]
and the ticket-articles belonging to that ticket:
[
{
"id": 130,
"ticket_id": 53,
"type_id": 1,
"sender_id": 1,
"from": "Stefan Weichinger <office#my.tld>",
"to": "info#company1.com",
"cc": null,
"subject": "Testanfrage Weichinger",
"reply_to": null,
"message_id": "<76d10a5b-64eb-7bfa-98c3-e31ed062802e#my.tld>",
"message_id_md5": "2bf547f5f570f6a8143ca8084110aee2",
"in_reply_to": null,
"content_type": "text/plain",
"references": null,
"body": "\nZum Test von Zammad-Emailing.\n\n-- \nViele Grüße | Stefan Weichinger | DW: | Mobil: \n",
"internal": false,
"preferences": {
"send-auto-response": true,
"is-auto-response": false
},
"updated_by_id": 3,
"created_by_id": 3,
"origin_by_id": null,
"created_at": "2022-11-15T07:19:04.078Z",
"updated_at": "2022-11-15T07:19:04.078Z",
"attachments": [],
"type": "email",
"sender": "Agent",
"created_by": "office#my.tld",
"updated_by": "office#my.tld"
},
{
"id": 131,
"ticket_id": 53,
"type_id": 1,
"sender_id": 1,
"from": "\"Stefan White via company1 Support\" <info#company1.com>",
"to": "office#my.tld",
"cc": "",
"subject": "Testanfrage Weichinger",
"reply_to": null,
"message_id": "<20221115071941.53.6087c1df-aa4c-4cbf-b79a-e2498239612b#ticket.company1.com>",
"message_id_md5": "07a9eee59e351c3d068badce3a56c7a0",
"in_reply_to": "<76d10a5b-64eb-7bfa-98c3-e31ed062802e#my.tld>",
"content_type": "text/html",
"references": null,
"body": "KLappt nun das ANtworten?<br><br><div data-signature=\"true\" data-signature-id=\"1\"> Stefan White<br><br>--<br> Super Support - Waterford Business Park<br> 5201 Blue Lagoon Drive - 8th Floor & 9th Floor - Miami, 33126 USA<br> Email: hot#example.com - Web: http://www.example.com/<br>--</div>",
"internal": false,
"preferences": {
"subtype": "reply",
"email_address_id": 1,
"delivery_retry": 1,
"delivery_channel_id": 3,
"delivery_status_message": null,
"delivery_status": "success",
"delivery_status_date": "2022-11-15T07:19:43.621Z"
},
"updated_by_id": 4,
"created_by_id": 4,
"origin_by_id": null,
"created_at": "2022-11-15T07:19:41.008Z",
"updated_at": "2022-11-15T07:19:43.622Z",
"attachments": [],
"type": "email",
"sender": "Agent",
"created_by": "sel#stefanwhite.com",
"updated_by": "sel#stefanwhite.com"
}
]
A freelancer has written a piece of nodejs that I can call via http-request.
That code needs both JSON-objects combined in one "body", like in:
{
"Ticket": {
"id": 53,
"group_id": 2,
"priority_id": 2,
"state_id": 2,
"organization_id": null,
"number": "740534",
"title": "Testanfrage Weichinger",
"owner_id": 3,
"customer_id": 3,
"note": null,
"first_response_at": "2022-11-15T07:19:04.078Z",
"first_response_escalation_at": null,
"first_response_in_min": 0,
"first_response_diff_in_min": 4320,
"close_at": null,
"close_escalation_at": null,
"close_in_min": null,
"close_diff_in_min": null,
"update_escalation_at": null,
"update_in_min": null,
"update_diff_in_min": null,
"last_contact_at": "2022-11-15T07:20:05.013Z",
"last_contact_agent_at": "2022-11-15T07:19:41.008Z",
"last_contact_customer_at": "2022-11-15T07:20:05.013Z",
"last_owner_update_at": "2022-11-15T12:08:48.875Z",
"create_article_type_id": 1,
"create_article_sender_id": 1,
"article_count": 3,
"escalation_at": null,
"pending_time": null,
"type": null,
"time_unit": null,
"preferences": {
"channel_id": 3,
"escalation_calculation": {
"first_response_at": "2022-11-15T07:19:04.078Z",
"last_update_at": "2022-11-15T07:20:05.013Z",
"last_contact_at": "2022-11-15T07:20:05.013Z",
"sla_id": 2,
"sla_updated_at": "2023-01-11T16:02:47.791Z",
"calendar_id": 2,
"calendar_updated_at": "2023-01-15T13:20:30.043Z",
"escalation_disabled": false
}
},
"updated_by_id": 3,
"created_by_id": 3,
"created_at": "2022-11-15T07:19:04.022Z",
"updated_at": "2023-01-16T07:40:29.206Z",
"datev_dokumentennummer": "",
"last_close_at": null
},
"articles": [
{
"id": 130,
"ticket_id": 53,
"type_id": 1,
"sender_id": 1,
"from": "Stefan Weichinger <office#my.tld>",
"to": "info#company1.com",
"cc": null,
"subject": "Testanfrage Weichinger",
"reply_to": null,
"message_id": "<76d10a5b-64eb-7bfa-98c3-e31ed062802e#my.tld>",
"message_id_md5": "2bf547f5f570f6a8143ca8084110aee2",
"in_reply_to": null,
"content_type": "text/plain",
"references": null,
"body": "\nZum Test von Zammad-Emailing.\n\n-- \nViele Grüße | Stefan Weichinger | DW: | Mobil: \n",
"internal": false,
"preferences": {
"send-auto-response": true,
"is-auto-response": false
},
"updated_by_id": 3,
"created_by_id": 3,
"origin_by_id": null,
"created_at": "2022-11-15T07:19:04.078Z",
"updated_at": "2022-11-15T07:19:04.078Z",
"attachments": [],
"type": "email",
"sender": "Agent",
"created_by": "office#my.tld",
"updated_by": "office#my.tld"
},
{
"id": 131,
"ticket_id": 53,
"type_id": 1,
"sender_id": 1,
"from": "\"Stefan White via company1 Support\" <info#company1.com>",
"to": "office#my.tld",
"cc": "",
"subject": "Testanfrage Weichinger",
"reply_to": null,
"message_id": "<20221115071941.53.6087c1df-aa4c-4cbf-b79a-e2498239612b#ticket.company1.com>",
"message_id_md5": "07a9eee59e351c3d068badce3a56c7a0",
"in_reply_to": "<76d10a5b-64eb-7bfa-98c3-e31ed062802e#my.tld>",
"content_type": "text/html",
"references": null,
"body": "KLappt nun das ANtworten?<br><br><div data-signature=\"true\" data-signature-id=\"1\"> Stefan White<br><br>--<br> Super Support - Waterford Business Park<br> 5201 Blue Lagoon Drive - 8th Floor & 9th Floor - Miami, 33126 USA<br> Email: hot#example.com - Web: http://www.example.com/<br>--</div>",
"internal": false,
"preferences": {
"subtype": "reply",
"email_address_id": 1,
"delivery_retry": 1,
"delivery_channel_id": 3,
"delivery_status_message": null,
"delivery_status": "success",
"delivery_status_date": "2022-11-15T07:19:43.621Z"
},
"updated_by_id": 4,
"created_by_id": 4,
"origin_by_id": null,
"created_at": "2022-11-15T07:19:41.008Z",
"updated_at": "2022-11-15T07:19:43.622Z",
"attachments": [],
"type": "email",
"sender": "Agent",
"created_by": "sel#stefanwhite.com",
"updated_by": "sel#stefanwhite.com"
}
]
}
In my n8n-workflow I can add js-code to do that, could someone help me writing this?
I googled around merging and concatenating json, but the additional adding of the "names" makes it harder for me (adding "Ticket:" and "articles:" ...). I am not a js-coder at all ... so far ;-)
Any help appreciated! thanks
Assuming you have your tickets stored in some variable named tickets and all your articles stored in some variable named articles. You can simply map your tickets to your new combined type as such.
let cominedTickes = tickets.map(ticket => ({
Ticket: ticket,
articles: articles.filter(article => article.ticket_id === ticket.id)
}));
You can simply filter the articles for each ticket by the ticket_id.
Related
I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?
hi im building application and i need to store data in txt file and retrieve it
the data is object like this .. .
[
{
"key": 0,
"id": 1,
"number": "1001",
"name": "سلعة ملموسة",
"offer_end_date": null,
"offer_start_date": null,
"components": [],
"quantity": "9",
"product": {
"id": 1,
"name": "سلعة ملموسة",
"number": "1001",
"product_id": null,
"foreign_name": "Product",
"can_be_sold": 1,
"can_be_purchased": 1,
"can_be_rented": 1,
"available_on_pos": 1,
"pos_quick_lunch": 1,
"available_on_manufacture": 1,
"product_category_id": 1,
"product_unit_type_id": null,
"location_id": null,
"area_id": null,
"discount_value": 10,
"balance": null,
"smallest_unit_id": 1,
"smallest_unit_barcode": null,
"smallest_unit_selling_price": 10,
"smallest_unit_cost": null,
"smallest_unit_selling_price_above": null,
"smallest_unit_selling_price_above_price": null,
"tax_value": 16,
"state_id": 1,
"warehouse_id": null,
"product_type_id": 1,
"product_policy_id": null,
"tax_user_id": null,
"user_id": null,
"get_specification_on_lines": null,
"is_products_has_expire_date": 1,
"is_products_has_patch_number": 1,
"is_products_has_serial_number": 1,
"offer_end_date": null,
"offer_start_date": null,
"last_purchase_date": null,
"last_purchase_purchase": null,
"last_purchase_price": null,
"last_purchase_discount": null,
"created_by": null,
"deleted_by": null,
"approved_by": null,
"approved_date": null,
"approved_state_id": null,
"note": null,
"created_at": "2022-03-04T06:52:16.000000Z",
"updated_at": "2022-03-04T06:52:16.000000Z",
"deleted_at": null,
"get_pos_product_componentss": [],
"get_pos_product_components": [],
"get_smallest_unit_id": {
"id": 1,
"name": "حبة",
"foreign_name": "unit",
"number": "1",
"created_by": 1,
"deleted_by": null,
"approved_by": null,
"approved_date": null,
"approved_state_id": null,
"note": null,
"created_at": "2022-03-04T06:52:15.000000Z",
"updated_at": "2022-03-04T06:52:15.000000Z",
"deleted_at": null
},
"get_product_offers": []
},
"smallest_unit_selling_price": 10,
"smallest_unit_selling_price_above": null,
"smallest_unit_selling_price_above_price": null,
"discount": 0,
"allowed_discount": 10,
"tax_value": 16,
"unit": "حبة",
"smallest_unit_id": 1,
"note": null,
"active": 1,
"price": 104.39999999999999
}
]
now this object i need to store it in file called text.txt
how can i store the object inside the file ..
and how can i retrieve the data using JavaScript ..
thanks ..
ive found solutions thats i can put the object in cookies but my problem with cookies they only allowing 4kb of data
never mind i found this solution ..
first of store data in localStorage like this ..
localStorage.setItem("orders", JSON.stringify(this.orders));
then access it like this ..
var orders = JSON.parse(localStorage.getItem('orders'));
console.log(orders);
I have the following API call returned values that has an id value
var sites =
{
"response": [
{
"id": 1433,
"name": "Bronx 1",
"address": "5288 McGlynn Hills",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1433/attributes"
},
{
"id": 1434,
"name": "Bronx 2",
"address": "126 Mann Divide",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1434/attributes"
}
]
}
I need to use the ID value from the call above an compare it to the following API response site_id value
var floors =
{
"response": [
{
"id": 118,
"label": "Crowded floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 100,
"site_common_area": 50,
"floor_common_area": 50,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=118",
"site_id": 1433,
"icon_scale_factor": 0.2,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/118/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/118/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1390"
]
},
{
"id": 119,
"label": "Normal floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 200,
"site_common_area": 0,
"floor_common_area": 200,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=119",
"site_id": 1453,
"icon_scale_factor": 0.7,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/119/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/119/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1391"
]
}
],
"count": 2
}
When site.id = floors.site_id I want to build a new key value pair that looks like this: only for the matched values
var match {floor.id: site.name}
I am having trouble looping over both and returning values any help is appreciated
Thanks
Hey #Abdullah Albyati,
I try to created what u asked but, it's actually not that usefull but here it is:
var floors =
{
"response": [
{
"id": 118,
"label": "Crowded floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 100,
"site_common_area": 50,
"floor_common_area": 50,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=118",
"site_id": 1452,
"icon_scale_factor": 0.2,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/118/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/118/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1390"
]
},
{
"id": 119,
"label": "Normal floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 200,
"site_common_area": 0,
"floor_common_area": 200,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=119",
"site_id": 1453,
"icon_scale_factor": 0.7,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/119/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/119/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1391"
]
}
],
"count": 2
};
var sites =
{
"response": [
{
"id": 1433,
"name": "Bronx 1",
"address": "5288 McGlynn Hills",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1433/attributes"
},
{
// "id": 1434,
"id": 1453,
"name": "Bronx 2",
"address": "126 Mann Divide",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1434/attributes"
}
]
}
var conbined = floors.response.reduce((obj, floor) => {
var site_id = floor.site_id;
var site = sites.response.find(site => site.id === site_id);
if(site) {
console.log(site.name);
return { ...obj, floor_site_id: site.name }
}
return obj;
}, {});
console.log(conbined);
In the data you gave there was no data to combine so i changed one of the id's. Hope this works for you 😊
Am trying to create a shopping cart in react native, my problem is whenever i add a product to the shopping cart it is added through the following action:
export const addToCart = (item) => {
return (dispatch) =>{
dispatch({
type:ADD_TO_CART,
payload: {item}});
}
}
this is the reducer:
import {REMOVE_FROM_CART,ADD_TO_CART,UPDATE_CART_QUANTITY,GET_CATEGORIES, GET_PRODUCTS,
MODAL_STATE,MODAL_STATE_HIDE,ADDRESS_CHANGED,SELECTED_ITEMS} from '../actions/types';
const INITIAL_STATE = {
products:'',
cart:[],
category:'',
isVisible:false,
address:'',
selectedItem:[]
}
export default function(state=INITIAL_STATE, action){
let cart = state.cart;
switch(action.type){
case ADD_TO_CART:
return{...state, cart:[...state.cart, action.payload]}
case REMOVE_FROM_CART:
return{cart:[...state.cart.filter(item => item.id != action.payload)]}
// {...state, cart:[...state.cart.filter((id)=>{ id !== action.payload})]}
case UPDATE_CART_QUANTITY:
return {
...state,
cart: state.cart.map(cart=> cart.id === action.payload.item.id ?
{ ...cart, quantity: action.payload.value} :
cart
)
};
case GET_CATEGORIES:
return{...state, category:action.payload}
case GET_PRODUCTS:
return{...state, products:action.payload}
case MODAL_STATE:
return{...state, isVisible:true}
case MODAL_STATE_HIDE:
return{...state, isVisible:false}
case ADDRESS_CHANGED:
return{...state, address:action.payload}
case SELECTED_ITEMS:
return{...state, selectedItem:[...state.selectedItem, action.payload]}
default:
return state
}
}
BUT when i try to access the cart through mapping state to props in the cart component, it returns undefined is not an object, when console log typeof(cart) from cart component it says its an object:
this is the mapstatetoprops function:
const mapStateToProps = (state) => {
return{
cartItems:state.product_reducer.cart,
modalValue:state.product_reducer.isVisible,
total: state.product_reducer.cart.reduce(
in the array
(accumulatedTotal, cartItem) =>
accumulatedTotal + cartItem.price * cartItem.quantity,
0
)
}
}
this is the json product data that i add to the cart there are two products with 7 and 8 as ids:
{
"product": [
{
"id": 8,
"name": "asad",
"quantity": 1,
"type": "already",
"description": null,
"price": "20000.00",
"ingredients": null,
"deliveryfee": "0.00",
"supplier": null,
"duration": "3",
"category_id": 3,
"created_at": "2020-05-03 15:03:23",
"updated_at": "2020-05-03 15:03:23",
"deleted_at": null,
"photo": {
"id": 19,
"model_type": "App\\Product",
"model_id": 8,
"collection_name": "photo",
"name": "5eaedd370c100_jamies-iced-green-tea",
"file_name": "5eaedd370c100_jamies-iced-green-tea.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 36610,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 19,
"created_at": "2020-05-03 15:03:24",
"updated_at": "2020-05-03 15:03:24",
"url": "http://192.168.0.112/kwenu/storage/app/public/19/5eaedd370c100_jamies-iced-green-tea.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/19/conversions/5eaedd370c100_jamies-iced-green-tea-thumb.jpg"
},
"sliderimages": [],
"tags": [
{
"id": 1,
"name": "Avocado",
"supplier": null,
"created_at": "2020-04-23 09:35:00",
"updated_at": "2020-04-23 09:35:00",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 8,
"product_tag_id": 1
},
"media": []
},
{
"id": 2,
"name": "cushew",
"supplier": "Fruit Salads",
"created_at": "2020-04-27 13:03:35",
"updated_at": "2020-04-27 13:03:35",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 8,
"product_tag_id": 2
},
"media": []
}
],
"media": [
{
"id": 19,
"model_type": "App\\Product",
"model_id": 8,
"collection_name": "photo",
"name": "5eaedd370c100_jamies-iced-green-tea",
"file_name": "5eaedd370c100_jamies-iced-green-tea.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 36610,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 19,
"created_at": "2020-05-03 15:03:24",
"updated_at": "2020-05-03 15:03:24",
"url": "http://192.168.0.112/kwenu/storage/app/public/19/5eaedd370c100_jamies-iced-green-tea.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/19/conversions/5eaedd370c100_jamies-iced-green-tea-thumb.jpg"
}
]
},
{
"id": 7,
"name": "Fruity",
"quantity": 1,
"type": "own",
"description": null,
"price": "18000.00",
"ingredients": null,
"deliveryfee": "0.00",
"supplier": null,
"duration": "1",
"category_id": 2,
"created_at": "2020-05-03 11:06:52",
"updated_at": "2020-05-03 11:06:52",
"deleted_at": null,
"photo": {
"id": 18,
"model_type": "App\\Product",
"model_id": 7,
"collection_name": "photo",
"name": "5eaea5c67a659_grilledchicken",
"file_name": "5eaea5c67a659_grilledchicken.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 13069,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 18,
"created_at": "2020-05-03 11:06:53",
"updated_at": "2020-05-03 11:06:56",
"url": "http://192.168.0.112/kwenu/storage/app/public/18/5eaea5c67a659_grilledchicken.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/18/conversions/5eaea5c67a659_grilledchicken-thumb.jpg"
},
"sliderimages": [],
"tags": [
{
"id": 1,
"name": "Avocado",
"supplier": null,
"created_at": "2020-04-23 09:35:00",
"updated_at": "2020-04-23 09:35:00",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 7,
"product_tag_id": 1
},
"media": []
},
{
"id": 2,
"name": "cushew",
"supplier": "Fruit Salads",
"created_at": "2020-04-27 13:03:35",
"updated_at": "2020-04-27 13:03:35",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 7,
"product_tag_id": 2
},
"media": []
}
],
"media": [
{
"id": 18,
"model_type": "App\\Product",
"model_id": 7,
"collection_name": "photo",
"name": "5eaea5c67a659_grilledchicken",
"file_name": "5eaea5c67a659_grilledchicken.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 13069,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 18,
"created_at": "2020-05-03 11:06:53",
"updated_at": "2020-05-03 11:06:56",
"url": "http://192.168.0.112/kwenu/storage/app/public/18/5eaea5c67a659_grilledchicken.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/18/conversions/5eaea5c67a659_grilledchicken-thumb.jpg"
}
]
}
]
}
THE PROBLEM IS INSTEAD OF STATE RETURNING cart AS AN ARRAY OF OBJECTS, IT RETURNS AN OBJECT OF OBJECTS, THANK YOU IN ADVANCE
i see addToCart action take the payload as an object { item }
and you try to access in reducer by action.payload without item
so
you can change
case ADD_TO_CART:
return{...state, cart:[...state.cart, action.payload.item]}
Or just update add to cart to be like so && all actions should be same
export const addToCart = (payload) => {
return (dispatch) =>{
dispatch({
type:ADD_TO_CART,
payload
}
}
Fixed it by changing the name of the cart array in the reducer from
const INITIAL_STATE = {
products:'',
cart:[],
category:'',
isVisible:false,
address:'',
selectedItem:[]
}
to:
const INITIAL_STATE = {
products:'',
carts:[],
category:'',
isVisible:false,
address:'',
selectedItem:[]
}
and the creating a class function for rendering the items in the cart component which i supplied to the renderitem function in the flatlist now the cart returns an array of objects. THANK YOU MUSTAFA FOR YOUR CONCERN
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I need to create a table from selected data generated by some rental software in json format via an api. The json data supplied is a list of products, and is quite extensive with objects containing other objects and arrays.
The problem comes when I need to retrieve the data from an object within an object. I want to get Name, weight and Rental Price form the data below. The rental price is in the rental_rate object.
{
"products": [
{
"id": 1404,
"name": "Product 1",
"type": "Product",
"tag_list": [],
"description": "",
"allowed_stock_type": 1,
"allowed_stock_type_name": "Rental",
"stock_method": 1,
"stock_method_name": "Bulk",
"buffer_percent": "50.0",
"post_rent_unavailability": 0,
"replacement_charge": "0.0",
"weight": "0.5",
"barcode": "#st2078",
"active": true,
"accessory_only": false,
"system": false,
"discountable": true,
"rental_rate": {
"item_id": 1404,
"store_id": 1,
"transaction_type": 1,
"rate_definition_id": 3,
"price": "10.0",
"deposit": "0.0",
"category_prices": [],
"properties": {
"day_cost": "0.0",
"day_price": "0.0",
"hour_cost": "0.0",
"hour_price": "0.0",
"__value_types": "---\nday_price: BigDecimal\nhour_price: BigDecimal\ndistance_price: BigDecimal\nflat_rate_price: BigDecimal\nday_cost: BigDecimal\nhour_cost: BigDecimal\ndistance_cost: BigDecimal\nflat_rate_cost: BigDecimal\n",
"distance_cost": "0.0",
"distance_price": "0.0",
"flat_rate_cost": "0.0",
"flat_rate_price": "0.0"
},
"priority": 0,
"date_range": "1900-01-01...3000-01-01"
},
"sale_rate": null,
"product_group_id": 5,
"tax_class_id": 2,
"rental_revenue_group_id": 1,
"sale_revenue_group_id": null,
"created_at": "2017-02-06T00:49:47.755Z",
"updated_at": "2017-02-06T00:49:47.755Z",
"custom_fields": {
"barcode_notes": "Actual Leg Length is: 3'",
"product_serial_number": ""
},
"product_group": {
"id": 5,
"name": "Staging",
"description": "",
"created_at": "2017-02-05T22:20:53.465Z",
"updated_at": "2017-02-05T22:20:53.465Z",
"custom_fields": {}
},
"tax_class": {
"id": 2,
"name": "VAT Standard"
},
"icon": null,
"rental_revenue_group": {
"id": 1,
"name": "Rental",
"description": "",
"active": true
},
"sale_revenue_group": null,
"accessories": [],
"alternative_products": [],
"attachments": [],
"rental_rates": [
{
"id": 1782,
"store_id": null,
"store_name": "",
"rate_definition_id": 3,
"rate_definition_name": "3 Day Week Rate",
"starts_at": null,
"ends_at": null,
"price": "10.0",
"category_prices": []
}
],
"sale_rates": []
},
{
"id": 2395,
"name": "Product 2",
"type": "Product",
"tag_list": [],
"description": "",
"allowed_stock_type": 1,
"allowed_stock_type_name": "Rental",
"stock_method": 2,x
"stock_method_name": "Serialised",
"buffer_percent": "50.0",
"post_rent_unavailability": 0,
"replacement_charge": "0.0",
"weight": "45.0",
"barcode": "",
"active": true,
"accessory_only": false,
"system": false,
"discountable": true,
"rental_rate": {
"item_id": 2395,
"store_id": 1,
"transaction_type": 1,
"rate_definition_id": 3,
"price": "0.0",
"deposit": "0.0",
"category_prices": [],
"properties": {
"day_cost": "0.0",
"day_price": "0.0",
"hour_cost": "0.0",
"hour_price": "0.0",
"__value_types": "---\nday_price: BigDecimal\nhour_price: BigDecimal\ndistance_price: BigDecimal\nflat_rate_price: BigDecimal\nday_cost: BigDecimal\nhour_cost: BigDecimal\ndistance_cost: BigDecimal\nflat_rate_cost: BigDecimal\n",
"distance_cost": "0.0",
"distance_price": "0.0",
"flat_rate_cost": "0.0",
"flat_rate_price": "0.0"
},
"priority": 0,
"date_range": "1900-01-01...3000-01-01"
},
"sale_rate": null,
"product_group_id": 6,
"tax_class_id": 2,
"rental_revenue_group_id": 1,
"sale_revenue_group_id": null,
"created_at": "2017-02-06T00:50:35.834Z",
"updated_at": "2017-02-06T00:50:35.834Z",
"custom_fields": {
"barcode_notes": "",
"product_serial_number": ""
},
"product_group": {
"id": 6,
"name": "Cases",
"description": "",
"created_at": "2017-02-05T22:20:53.509Z",
"updated_at": "2017-02-05T22:20:53.509Z",
"custom_fields": {}
},
"tax_class": {
"id": 2,
"name": "VAT Standard"
},
"icon": null,
"rental_revenue_group": {
"id": 1,
"name": "Rental",
"description": "",
"active": true
},
"sale_revenue_group": null,
"accessories": [],
"alternative_products": [],
"attachments": [],
"rental_rates": [
{
"id": 2773,
"store_id": null,
"store_name": "",
"rate_definition_id": 3,
"rate_definition_name": "3 Day Week Rate",
"starts_at": null,
"ends_at": null,
"price": "0.0",
"category_prices": []
}
],
"sale_rates": []
}
],
"meta": {
"total_row_count": 1376,
"row_count": 2,
"page": 1,
"per_page": 2
}
}
and here is the JS I am using to get the data:
$(document).ready( function() {
$.getJSON( 'https://myapi.com/products', function(data) {
$.each(data.products, function() {
$("table#prod").append("<tr><td>" + this['name'] + "</td><td>" + this['rental_rate.price'] + "</td><td>" + this['weight'] + "kg</td></tr>");
}); }); });
This works fine for name and weight, but not rental price. I have done a thorough search of most places on the internet and not found an answer - my javascript knowledge is limited, which probably means I am going about this all wrong, or not describing it well enough...
Any help or improved methods would be much appreciated!
this.name gets you the name
this.rental_rate gets you the nested rental rate object.
this.rental_rate.price gets you the price.
You can similarly use square bracket notation, but people often only do this when dot syntax won't work (because of spaces in the key).
e.g.
this["name"]
this["rental_rate"]["price"]
this["Invalid Key when accessed via dot syntax but fine with square brackets"]