How to get json data from multiple object levels [duplicate] - javascript

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"]

Related

Partition messages by date, last read in angular

I want to partition my messages by date for my chat application(Similar to the Microsoft teams app)
The message data will be like
[
{
"id": 577,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "John J"
},
"body": "test test",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T07:59:28.873+00:00"
},
{
"id": 578,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Don V"
},
"body": "ok",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T08:02:26.262+00:00"
},
{
"id": 628,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Sam GP"
},
"body": "Hola",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:27:48.038+00:00"
},
{
"id": 629,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Rawn OP"
},
"body": "ek",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:29:36.705+00:00"
},
{
"id": 630,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Paul John"
},
"body": "hi",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:30:36.695+00:00"
},
{
"id": 631,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Dennise V"
},
"body": "knock knock",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:32:38.035+00:00"
},
{
"id": 632,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Shawn"
},
"body": "who's this",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:25.985+00:00"
},
{
"id": 633,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Pater B"
},
"body": "I see",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:30.783+00:00"
},
{
"id": 634,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Cera LO"
},
"body": "Will call you later",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:38.268+00:00"
},
{
"id": 642,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Rose BH"
},
"body": "hello???????",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-21T05:25:56.642+00:00"
}
]
I need to arrange these data to show the messages by date like
------------------------------Sep 30-----------------------------
Messages sent/received on sep 30
------------------------------Yesterday--------------------------
Messages sent/received on yesterday
------------------------------Last read-------------------------
------------------------------Oct30-----------------------------
------------------------------Yesterday-------------------------
------------------------------Today-----------------------------
For displaying "Sep 30", "yesterday", and "Today" I've created a pipe that converts the timestamp into the month and "yesterday", "today" etc.
I already got the solution to arrange the message by date. But I have to arrange it under the "Last read" block too. Same as by dates. the flag "readStatus" is sed to check whether the message has been read or not" If it is false is should come under "Last read".
Any ideas? Any help will be appreciated.
I imagine you can has something like (if your data is in a variable "data"
dataOrder = {
readed: this.group(this.data.filter((x) => x.readStatus)),
notReaded: this.group(this.data.filter((x) => !x.readStatus)),
};
group(data: any[]) {
return data.reduce((a, b) => {
const dateTime=new Date(b.createdDateTime.substr(0,10)+"T00:00:00.00+00:00")
.getTime()
const element = a.find((x) => x.dateTime == dateTime);
if (!element) a.push({ dateTime:dateTime,data: [b] });
else element.data.push(b);
return a;
}, []);
}
See that "dataOrder" has two properties "readed" and "notReaded", each one are arrays of objects in the way
{
dateTime:a dateTime,
data:an array with the messages
}
This makes easy indicate the date using Angular date pipe, and loop over the messages
So, an .html like
<h1>Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.readed }"
></ng-container>
<h1>Not Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.notReaded }"
></ng-container>
<ng-template #messagedata let-data>
<div *ngFor="let readed of data">
{{ readed.dateTime | date }}
<div *ngFor="let message of readed.data">
{{ message.createdDateTime }} - {{ message.body }}
</div>
</div>
</ng-template>
I use the same template for both type of messages
A stackblitz
Update As the dataOrder it's only change at fisrt is better use a function
getDataOrdered(data:any[])
{
return {
readed: this.group(data.filter((x) => x.readStatus)),
notReaded: this.group(data.filter((x) => !x.readStatus)),
};
}
Then, we can, each time some message change its "readStatus" we can do
this.dataOrder=this.getDataOrdered(this.data)

mongoDB - How do master-detail structure grouped detail collection specific fields summary

In a mongodb database with a master-detail structure, how do I ensure that the data in the detail table is grouped according to the status area while querying the master table. For example ...
Master, Row, Job, Fields, [Detail Status Grouped Count / Summary Object]
Edited:
sms_jobs collection example data is :
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z")
}
sms_job_details collection example data is :
// 1
{
"_id": NumberInt("221462"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "waiting", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 2
{
"_id": NumberInt("221463"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "failed", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 3
{
"_id": NumberInt("221464"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "success", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
I experimented for approximately 4-5 hours. I could get the closest result with the following query.
db.getCollection("sms_jobs").aggregate([{
$lookup: {
from: "sms_job_details",
localField: "_id",
foreignField: "sms_job_id",
as: "data"
}
}, {
$unwind: "$data"
}, {
$group: {
_id: {
id: "$_id",
status: "$data.status"
},
qty: {
$sum: 1
}
}
}, {
$project: {
_id: "$_id.id",
qty: 1,
status: "$_id.status"
}
}])
And get this result :
// 1
{
"qty": 22145,
"_id": NumberInt("4"),
"status": "success"
}
// 2
{
"qty": 1,
"_id": NumberInt("3"),
"status": "success"
}
// 3
{
"qty": 22142,
"_id": NumberInt("1"),
"status": "success"
}
// 4
{
"qty": 1,
"_id": NumberInt("1"),
"status": "failed"
}
// 5
{
"qty": 2,
"_id": NumberInt("1"),
"status": "waiting"
}
// 6
{
"qty": 1,
"_id": NumberInt("3"),
"status": "failed"
}
// 7
{
"qty": 3,
"_id": NumberInt("3"),
"status": "waiting"
}
What do I want ?
The query result I want is as follows.
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z"),
// Added part...
"status_countes": {
"success": NumberInt("20"),
"failed": NumberInt("2"),
"waiting": NumberInt("11"),
"canceled": NumberInt("0"),
"total": NumberInt("33")
},
}
Thank you in advance for your help...

Loop through JSON response and return values that matches another JSON response into a new key value

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 😊

How to deep merge objects in react js

{"activities": [
{
"actor": {
"id": 409,
"avatar": "",
"first_name": "Sakthi",
"last_name": "Vel",
"headline": null,
"is_online": false,
},
"foreign_id": "post.UsPost:253",
"id": "ed50e218-f3e8-11e8-8080-800132d8e9c0",
"object": {
"id": 253,
"comments": 0,
"likes": 0,
"files": [
{
"id": 112,
"file": "",
"content_type": "video/mp4",
"file_type": "video",
"created_at": "2018-11-29T15:10:38.524836Z"
}
],
"post_type": "post",
"is_bookmarked": false,
"is_liked": false,
"link": "/post/api/v1/253/",
"target": "post.UsPost:253",
"foreign_id": "post.UsPost:253",
"actor": {
"id": 409,
"avatar": "",
"first_name": "Sakthi",
"last_name": "Vel",
"headline": null,
"is_online": false,
},
"text": "#Multiple video (.mp4) test. Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.",
"skills": [
"VFX"
],
"created_at": "2018-11-29T15:10:37.426332Z",
"is_link": true,
"view_count": 0,
"created_by": 409
},
"origin": "user:409",
"target": "",
"time": "2018-11-29T15:10:37.426332",
"type": "post",
"verb": "posted"
}
{
"activities": [
{
"actor": {
"id": 64,
"last_name": "",
"headline": "Learning is my Passion",
"is_online": false,
"username": "Uchenna1"
},
"foreign_id": "post.UsPost:183",
"id": "447f6710-eb08-11e8-8080-8001369e78cd",
"object": {
"id": 183,
"comments": 1,
"likes": 1,
"files": [
{
"id": 87,
"content_type": "image/jpg",
"file_type": "image",
"created_at": "2018-11-18T08:02:18.759309Z"
}
],
"post_type": "post",
"is_bookmarked": false,
"is_liked": false,
"link": "/post/api/v1/183/",
"target": "post.UsPost:183",
"foreign_id": "post.UsPost:183",
"actor": {
"id": 64,
"first_name": "Uchenna",
"last_name": "",
"headline": "Learning is my Passion",
"is_online": false,
"username": "Uchenna1"
},
"text": "This is codigo",
"skills": [
"Javascript"
],
"created_at": "2018-11-18T08:02:17.626600Z",
"is_link": true,
"view_count": 10,
"created_by": 64
},
"origin": "user:64",
"target": "",
"time": "2018-11-18T08:02:17.626600",
"type": "post",
"verb": "posted"
}
],
"activity_count": 1,
"actor_count": 1,
"created_at": "2018-11-18T08:02:18.647108",
"group": "posted_2018-11-18",
"id": "451b1eab-eb08-11e8-8080-80007915e2b6.posted_2018-11-18",
"is_read": false,
"is_seen": true,
"updated_at": "2018-11-18T08:02:18.647108",
"verb": "posted"
}
I am facing issue in merging two object. Below is the snap of two object and result.
Here in the above image I wan to merge Old Data and new Data
but after merging getting wrong output i.e new updated data.
I am using command to do it.
let newData = { ...a , ...b }
console.log('new updated data: ',newData)
also I am performing this operation in redux action before dispatching.
Here {"activities": [....],....} is one object and I want to merge with the below one.
Can you clarify do your objects have a child that are objects or arrays and if you mean it's not merging those things or is it not merging anything at all?
for e.g:
let oldData = {
key: value,
key1: { childkey1: value1 }
}
if you have something like this and the problem is like I explained. It's because javascript doesn't do deep merge. it does a shallow merge.
Easiest option would be use a library like lodash that has a function for deep merge.

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