Trying to access object in Api array and count length - javascript

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'

Related

How to properly add a new object into the paginated field value into Apollo cache?

I have a complex graphql object/type that contains complex fields where value is the pagination data. One of the fields called comments and it contains the comments pagination data. I want to use the optimistic-ui approach and manually add the new Comment, when the user creates it, to the comments field value before the server mutation execution, and in this way I expect to show the user the freshly created comment while the mutation is executing on the server.
I'm really wondering about the best way how to do that?
I tried manually create the pagination node and push it inside the original comments nodes however I received an error: TypeError: Cannot add property 2, object is not extensible
I tried to clone the original comments value to be able to modify it but nothing helps somehow.
So I'd like to interest in some way how I could handle this problem.
I'll appreciate any help/information
P.S. Here is the code examples
The whole source Article object
{
"__typename": "Article",
"id": "607559b181072e34ecf7af25",
"createdAt": "2021-04-13T08:43:29.846Z",
"liked": false,
"likes": 0,
"commentsThreadId": "607559b181072e34ecf7af24",
"comments": {
"__typename": "CommentsConnection",
"totalCount": 2,
"pageInfo": {
"__typename": "PageInfo",
"hasNextPage": false,
"startCursor": "NjA3NTY4N2Y4MTA3MmUzNGVjZjdhZjI5",
"endCursor": "NjA5ZTRlMmIyM2U5NmEzZGRjOTQwMTIz",
"hasPreviousPage": false,
"count": 2
},
"edges": [
{
"__typename": "CommentEdge",
"node": {
"__typename": "Comment",
"id": "6075687f81072e34ecf7af29",
"text": "Comments like this are just amazing. YavatarImgUrlou can write whatever you want and after that, you can check the result of this. It can have more than 3 lines",
"liked": false,
"likes": 0,
"createdAt": "2021-04-13T09:46:39.806Z",
"owner": {
"__typename": "UserBase",
"id": "60658c4632aaea36205cffa2",
"firstName": "David",
"lastName": null,
"username": "david1",
"numericId": "3321"
}
}
},
{
"__typename": "CommentEdge",
"node": {
"__typename": "Comment",
"id": "609e4e2b23e96a3ddc940123",
"text": "Some simple comment guys",
"liked": false,
"likes": 0,
"createdAt": "2021-05-14T10:17:15.057Z",
"owner": {
"__typename": "UserBase",
"id": "608156675ca92e56749d71fc",
"firstName": "Sviat",
"lastName": null,
"username": "sviat1",
"numericId": "9421"
}
}
}
]
},
"author": {
"__typename": "User",
"id": "60754dda81072e34ecf7af13",
"imageUrl": null,
"firstName": "John",
"lastName": "Peterson",
"username": "john1",
"numericId": "3659"
},
"topics": [
{
"__typename": "Topic",
"id": "60658c8c470f285c18652917",
"name": "libsep"
},
{
"__typename": "Topic",
"id": "60658c89521b0e5c18daf3d6",
"name": "huribu"
}
]
}
The code I used to update the comments field
const { getArticle: cachedArticle } = apolloClient.readQuery({
query: GET_ARTICLE_QUERY,
variables: {
// Provide any required variables here
id: article.id,
},
});
const newComment = {
__typename: "Comment",
id: "6075687f81072e34ecf7af29",
text: 'Shiny New Comment Text',
liked: false,
likes: 0,
createdAt: "2021-04-13T09:46:39.806Z",
owner: {
__typename: "UserBase",
id: "60658c4632aaea36205cffa2",
firstName: "David",
lastName: null,
username: "david1",
numericId: "3321",
},
};
// Tried to create the new object that allowed to modify
const newComments = { ...cachedArticle.comments };
// got an error at this stage
newComments.edges.push({
__typename: "CommentEdge",
node: newComment,
});

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.

Need assistance concatenating a string request together in JavaScript

In JavaScript I am sending an https request to a server. I receive the data back I am looking for but it comes in batches. Depending on the size of the data I'm requesting could be from 2-50 different batches. I need to get them all together so I can parse and pull the data I need from an array. The data I receive is pasted below. You can see there is a date and time stamp at the beginning of the first batch and another after "rows":. Those are added by the debugger I am using which is how I know they come in separate. My question is:
1) How do i get the strings concatenated together
2) Which is the best way to get in an array so I can choose the data I want?
2018 - 03 - 08 T21: 09: 18.913 Z f657fe40 - 2314 - 11e8 - 8273 - 19289 d6ed567 {
"id": 12345678,
"name": "Dummy sheet",
"version": 1,
"totalRowCount": 1,
"accessLevel": "ADMIN",
"effectiveAttachmentOptions": ["BOX_COM", "GOOGLE_DRIVE", "FILE", "EGNYTE", "ONEDRIVE", "DROPBOX", "EVERNOTE"],
"ganttEnabled": false,
"dependenciesEnabled": false,
"resourceManagementEnabled": false,
"cellImageUploadEnabled": true,
"userSettings": {
"criticalPathEnabled": false,
"displaySummaryTasks": true
},
"permalink": "https://app.smartsheet.com/b/home?lx=rxeuvsB26BVmyEpa6OYxUA",
"createdAt": "2018-03-06T14:29:32Z",
"modifiedAt": "2018-03-06T14:51:59Z",
"columns": [{
"id": 3114821425096580,
"index": 0,
"title": "Primary Column",
"type": "TEXT_NUMBER",
"primary": true,
"validation": false,
"width": 150
}, {
"id": 7618421052467076,
"index": 1,
"title": "Column2",
"type": "TEXT_NUMBER",
"validation": false,
"width": 150
}, {
"id": 1988921518253956,
"index": 2,
"title": "Column3",
"type": "TEXT_NUMBER",
"validation": false,
"width": 150
}, {
"id": 6492521145624452,
"index": 3,
"title": "Column4",
"type": "TEXT_NUMBER",
"validation": false,
"width": 150
}, {
"id": 4240721331939204,
"index": 4,
"title": "Column5",
"type": "TEXT_NUMBER",
"validation": false,
"width": 150
}, {
"id": 8744320959309700,
"index": 5,
"title": "Column6",
"type": "TEXT_NUMBER",
"validation": false,
"width": 150
}],
"rows": 2018 - 03 - 08 T21: 09: 18.932 Z f657fe40 - 2314 - 11e8 - 8273 - 19289 d6ed567[{
"id": 573049024079748,
"rowNumber": 1,
"expanded": true,
"createdAt": "2018-03-06T14:51:59Z",
"modifiedAt": "2018-03-06T14:51:59Z",
"cells": [{
"columnId": 3114821425096580,
"value": 123456.0,
"displayValue": "$123,456.00"
}, {
"columnId": 7618421052467076
}, {
"columnId": 1988921518253956
}, {
"columnId": 6492521145624452
}, {
"columnId": 4240721331939204
}, {
"columnId": 8744320959309700
}]
}]
}
It's hard to tell from your description which strings you're trying to concatenate -- whole blobs of JSON, certain strings from within the JSON?
I can at least say that an efficient way to concatenate strings is to push them all into an array, then join the array into one string.
var builder = [];
builder.push(string1);
builder.push(string2);
builder.push(string3);
...
var result = builder.join('');
I'm not sure exactly what you mean by "get in an array" either, but if you're talking about turning all of one string into an array with each character as a individual item, string.split('') will do that.

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);

Can't get value of Object in Javascript , nodejs, stripe library

Im trying to get a value "status" from "customer" object with this simple script:
console.log(JSON.stringify(customer.subscriptions.data.plan.status));
When i execute this function, the console returns me:
TypeError: Cannot read property 'data' of undefined
"customer" Object:
customer: {
"object":"customer",
"created":xxxxxx,
"id":"xxxxxxx",
"livemode":false,
"description":null,
"email":"xxxx#xxxx.com",
"shipping":null,
"delinquent":false,
"metadata":{},
"subscriptions":{
"object":"list",
"total_count":1,
"has_more":false,
"url":"/v1/customers/xxxxxxxxx/subscriptions",
"data":[{
"id":"xxxxxxxxx",
"plan":{
"interval":"month",
"name":"xxxxxx",
"created":xxxxx,
"amount":xxxxx,
"currency":"eur",
"id":"6month",
"object":"plan",
"livemode":false,
"interval_count":6,
"trial_period_days":null,
"metadata":{},
"statement_descriptor":null,
"statement_description":null},
"object":"subscription",
"start":xxxxx,
"status":"active",
...,
Please help me.
Thanks.
The error doesn't match up with the data. It should be that it can't read status of undefined. This is because customer does have subscriptions, and subscriptions does have data, but then you're treating data as though it had a plan property, which it doesn't. data refers to an array, the first entry of which has a plan property. Also note that status is not a property of plan, it's a property of the same object that plan is a property of.
So accessing the first entry's status would be:
customer.subscriptions.data[0].status
// Note -------------------^^^
If there are subsequent entries in data, they would be at indexes 1, 2, 3, etc.
Example:
var customer = {
"object": "customer",
"created": "xxxxxx",
"id": "xxxxxxx",
"livemode": false,
"description": null,
"email": "xxxx#xxxx.com",
"shipping": null,
"delinquent": false,
"metadata": {},
"subscriptions": {
"object": "list",
"total_count": 1,
"has_more": false,
"url": "/v1/customers/xxxxxxxxx/subscriptions",
"data": [
{
"id": "xxxxxxxxx",
"plan": {
"interval": "month",
"name": "xxxxxx",
"created": "xxxxx",
"amount": "xxxxx",
"currency": "eur",
"id": "6month",
"object": "plan",
"livemode": false,
"interval_count": 6,
"trial_period_days": null,
"metadata": {},
"statement_descriptor": null,
"statement_description": null
},
"object": "subscription",
"start": "xxxxx",
"status": "active"
}
]
}
};
document.body.innerHTML = customer.subscriptions.data[0].status;

Categories

Resources