How to deep merge objects in react js - javascript

{"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.

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)

JSON not indexing correctly

I have this JSON:
[
{
"type": "GUILD_TEXT",
"deleted": false,
"guild": "898666651547996200",
"guildId": "898666651547996200",
"parentId": "903388176100495390",
"permissionOverwrites": [
"900991433576689675",
"917426278003523604",
"898666651547996200",
"898825198709641246"
],
"messages": [
"928781911982219307"
],
"threads": [],
"nsfw": false,
"id": "903388255528042566",
"name": "updates",
"rawPosition": 41,
"topic": null,
"lastMessageId": "928781911982219307",
"rateLimitPerUser": 0,
"createdTimestamp": 1635454944260
}
]
(call = the json)
Shouldn't this be returning "updates": call[0]["name"]
Via JS, it is returning undefined.
call[0] is returning as {
I've tried it on various other languages and it has been working as intended... just not in JS.
It does work:
const call = [{
"type": "GUILD_TEXT",
"deleted": false,
"guild": "898666651547996200",
"guildId": "898666651547996200",
"parentId": "903388176100495390",
"permissionOverwrites": [
"900991433576689675",
"917426278003523604",
"898666651547996200",
"898825198709641246"
],
"messages": [
"928781911982219307"
],
"threads": [],
"nsfw": false,
"id": "903388255528042566",
"name": "updates",
"rawPosition": 41,
"topic": null,
"lastMessageId": "928781911982219307",
"rateLimitPerUser": 0,
"createdTimestamp": 1635454944260
}]
console.log(call[0]["name"]) // updates
const callString = JSON.stringify(call)
console.log(JSON.parse(callString)[0]["name"]) // updates
I tried
var name= call[0].name;
and
var name= call[0]["name"];
evertything is working properly returning "updates".

Trying to access object in Api array and count length

Trying to access the mythic object and print the length of mythic's that exist in the account but unsure how to access it as its nested in the array. Api output is below Javascript. Just not sure exactly what I can use to get its length as I used json.mythic.length and that did not work. And Thank you very much to anyone who is able to help me with this problem.
function MyFunction(e) {
e.preventDefault();
var username = document.getElementById("username").value
document.getElementById("search").innerHTML = username;
const data = {
username, limit: 3000, offset: 0, rarities: [], markers: [], onSale: "", search: "" }
fetch("https://prod-eternal-backend.onrender.com/api/v1/moment/list" ,{
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
document.getElementById("moments").innerHTML ="Total Moments = " + json.moments.length;
var mythics = json.mythic.length * 50;
document.getElementById("gamer").innerHTML ="Gamer Score = " + mythics;
})
}
{
"moments": [
{
"id": 114375,
"playId": 536,
"setId": 16,
"serialNumber": 4,
"username": "pattonh84",
"userId": 1230,
"userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
"influencer": "YuggieTV",
"influencerId": "YuggieTV",
"influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/YuggieTV_square.png",
"playbackId": "QXMRHp9R4uFcSsCQkN7mBCDbSmFZdImdjeUHypEutRw",
"rarity": "mythic",
"createdAt": "2021-10-25T00:11:54.734962Z",
"setName": "Flow State",
"circulationCount": 30,
"title": "How Strong Could It Be?",
"imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/Let+Me+See+How+Strong+It+Is.png",
"packName": "Flow State",
"clipDate": "2021-09-26T02:55:28Z",
"tags": [
"funny"
],
"description": "Yuggie doing experiments in the name of science. Today's experiment is about how strong a watermelon could be.",
"game": "IRL",
"twitter": "yuggietv",
"staked": false,
"autographStatus": "false",
"discordUtility": false,
"markers": null
},
{
"id": 108262,
"playId": 565,
"setId": 16,
"serialNumber": 1,
"username": "pattonh84",
"userId": 1230,
"userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
"influencer": "Amouranth",
"influencerId": "Amouranth",
"influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/Amouranth.jpg",
"playbackId": "101L8XUOTCKkJW3USj6rtiJm5k4iTAwTIMqcxfPsr8QA",
"rarity": "mythic",
"createdAt": "2021-10-22T17:07:38.357172Z",
"setName": "Flow State",
"circulationCount": 30,
"title": "Mare Awareness",
"imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/amouranth+pretending+to+be+a+horse.png",
"packName": "Flow State",
"clipDate": "2021-09-26T04:21:46Z",
"tags": [
"funny"
],
"description": "Now a popular gif, this clip showcases a horse performance complete with galloping and internal monalogue.",
"game": "Just Chatting",
"twitter": "Amouranth",
"staked": false,
"autographStatus": "pending",
"autographRequestId": 2071,
"discordUtility": false,
"markers": null
},
{
"id": 114393,
"playId": 536,
"setId": 16,
"serialNumber": 22,
"username": "pattonh84",
"userId": 1230,
"userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
"influencer": "YuggieTV",
"influencerId": "YuggieTV",
"influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/YuggieTV_square.png",
"playbackId": "QXMRHp9R4uFcSsCQkN7mBCDbSmFZdImdjeUHypEutRw",
"rarity": "mythic",
"createdAt": "2021-10-22T03:35:24.934307Z",
"setName": "Flow State",
"forSale": true,
"circulationCount": 30,
"price": 200,
"title": "How Strong Could It Be?",
"imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/Let+Me+See+How+Strong+It+Is.png",
"packName": "Flow State",
"clipDate": "2021-09-26T02:55:28Z",
"tags": [
"funny"
],
"description": "Yuggie doing experiments in the name of science. Today's experiment is about how strong a watermelon could be.",
"game": "IRL",
"twitter": "yuggietv",
"staked": false,
"autographStatus": "false",
"discordUtility": false,
"productId": 67358,
"markers": null
}
],
"totalMoments": 3
}
You are trying to access a mythic property on your JSON object, but your data does not have such a property. I would recommend that you study more on JSON structure and accessing properties in javascript.
Basically, json.mythics checks for a property called mythics in the root level of your json object, the same way json.moments does. If your data was organized like:
{
"moments": [...],
"mythics": [...]
}
then you would access it with json.mythics
But your json only has a moments array of objects, some of which have a rarity property set to "mythic".
Assuming you want to filter out these elements from the array, a simple filter should suffice:
const mythics = json.moments.filter(moment => moment.rarity === 'mythic');
mythics.length // gives the length of the 'mythics'

trouble while parsing json

I am trying to react displayName in req
when I write
console.log(req.session.passport.user._raw)
the output is:
{
"kind": "plus#person",
"etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/XiR7kPThRbzcIw-YLiARoF22TMY\"",
"emails": [
{
"value": "rajanlagah#gmail.com",
"type": "account"
}
],
"objectType": "person",
"id": "100428644453494579140",
"displayName": "Rajan Lagah",
"name": {
"familyName": "Lagah",
"givenName": "Rajan"
},
"url": "https://plus.google.com/100428644453494579140",
"image": {
"url": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
"isDefault": true
},
"isPlusUser": true,
"language": "en",
"circledByCount": 0,
"verified": false
}
Now the from this object I am trying to get kind (say)
console.log(req.session.passport.user._raw.kind)
then the output is undefined
Can any one tell my mistake?
Is req.session.passport.user._raw a string? You may need to parse it first, eg:
var data = JSON.parse(req.session.passport.user._raw);
console.log(data.kind);

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

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

Categories

Resources