Accessing nested JSON object with JavaScript [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 months ago.
I am trying to access a nested JSON object and display it within the console.
Here is my JSON
{
"currentUser": {
"image": {
"png": "./images/avatars/image-juliusomo.png",
"webp": "./images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"comments": [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "./images/avatars/image-amyrobson.png",
"webp": "./images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "./images/avatars/image-maxblagun.png",
"webp": "./images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [
{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "./images/avatars/image-ramsesmiron.png",
"webp": "./images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
}
},
]
}
}
I am trying to access the reply by doing console.log(data.comments.replies); When i do this I get the following error in the console.
TypeError: comments.replies is undefined
Here is my code
fetch('./data.json', {
method: 'GET',
headers: {
'Accept': 'application/json',
},
})
.then((response) => response.json())
.then((data) => {
console.log(data.comments.replies);
})
.catch((error) => {
console.log(error);
});
I would like to loop over the array in order to display the information in html. I am un clear how to do this

Use index
data.comments[index].replies
Example:
data.comments[1].replies
const data = {
"currentUser": {
"image": {
"png": "./images/avatars/image-juliusomo.png",
"webp": "./images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"comments": [{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "./images/avatars/image-amyrobson.png",
"webp": "./images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "./images/avatars/image-maxblagun.png",
"webp": "./images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "./images/avatars/image-ramsesmiron.png",
"webp": "./images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
}
}]
}
]
}
console.log(data.comments[1].replies)

Related

How to flatten React state of comment section?

This is my data:
{
"currentUser": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"comments": [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-amyrobson.png",
"webp": "/src/assets/images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-maxblagun.png",
"webp": "/src/assets/images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [
{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-ramsesmiron.png",
"webp": "/src/assets/images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
}
},
{
"id": 4,
"content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
"createdAt": "2 days ago",
"score": 2,
"replyingTo": "ramsesmiron",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
}
}
]
}
]
}
and this is how i'd want it to look like, each comment to store the replies id's
{
"currentUser": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"comments": [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-amyrobson.png",
"webp": "/src/assets/images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-maxblagun.png",
"webp": "/src/assets/images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [ 3, 4 ]
},
{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-ramsesmiron.png",
"webp": "/src/assets/images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
}
},
{
"id": 4,
"content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
"createdAt": "2 days ago",
"score": 2,
"replyingTo": "ramsesmiron",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
}
}
]
}
So far I've used the data as it was, and I had a hard time setting the state later, and after reading the react docs (https://beta.reactjs.org/learn/choosing-the-state-structure#avoid-deeply-nested-state) I understood why it was so hard to manage. But the docs don't have any methods on how to flatten it
While for huge lists this is really not advisable, you can still do something like this
const replies = [];
// commentData is your incoming data
const data = {...commentData,
comments: commentData.comments.map(comment => {
if(comment.replies.length) {
comment.replies = comment.replies.map(reply => {
replies.push(reply);
return reply.id;
})
}
return comment;
})
};
data.comments = data.comments.concat(replies);
Remember that this is not very flexible in cases where replies might again have comments/replies ( nested objects )
JS Fiddle - https://jsfiddle.net/7d61jsm3/

How can I get the created by and updated by fields in StrapiJS?

I've just started using StrapiJS, and it's really great so far, but now I've come across a problem.
When creating adding some data to the database, Strapi automatically creates some fields - like created_by and updated_by fields, but I'm not getting them in the API response.
This is the data stored in MongoDB:
{
"_id": {
"$oid": "606fd90b0057c05954d29f50"
},
"likes": 0,
"dislikes": 0,
"Title": "Why is this not working?",
"Subtitle": "I really don't know",
"slug": "why-is-this-not-working",
"content": "**I DO NOT KNOW**",
"published_at": {
"$date": "2021-04-09T04:33:17.304Z"
},
"createdAt": {
"$date": "2021-04-09T04:33:15.232Z"
},
"updatedAt": {
"$date": "2021-04-09T04:33:17.316Z"
},
"__v": 0,
"created_by": {
"$oid": "606f1a45af15265f780983ce"
},
"updated_by": {
"$oid": "606f1a45af15265f780983ce"
}
}
And this is the API response:
{
"likes": 0,
"dislikes": 0,
"_id": "606fd90b0057c05954d29f50",
"Title": "Why is this not working?",
"Subtitle": "I really don't know",
"slug": "why-is-this-not-working",
"content": "**I DO NOT KNOW**",
"published_at": "2021-04-09T04:33:17.304Z",
"createdAt": "2021-04-09T04:33:15.232Z",
"updatedAt": "2021-04-09T04:33:17.316Z",
"__v": 0,
"id": "606fd90b0057c05954d29f50"
}
Is there a way to get the created of the data in the API response?
You will have to override the findOne method in your controller like below without the sanitize:
async findOne(ctx) {
const { id } = ctx.params;
const entity = await strapi.services.blogPost.findOne({ id });
// return sanitizeEntity(entity, { model: strapi.models.blogPost});
return entity;
}
refer:Backend customization
set populateCreatorFields=true in model.settings.json
This seem to work for me
Add
"populateCreatorFields": true
Add Optional
"publicAttributes": ["created_at", "updated_by"]
to
api/blog-post/models/blog-post.settings.json
...
"options": {
"increments": true,
"timestamps": true,
"draftAndPublish": true,
"populateCreatorFields": true
}
...

How to retrieve last subscribers with sorting such as in youtube?

I use simple method, such us
buildApiRequest('GET','/youtube/v3/channels',
{
'mySubscribers': true,
'maxResults': MaxResult,
'part': 'snippet'
}
It works, but in result I can't see how I can sort them.
I need last MaxResult subscribers, and I wanna sort them by join date on my channel.
The subscriptions.list and subscriberSnippet with myRecentSubscribers set to true returns a list of resent subscribers to your channel. It does not return all of them.
If you check the response you will notice there is no date. You will not be able to see when someone subscribed.
"subscriberSnippet": {
"title": string,
"description": string,
"channelId": string,
"thumbnails": {
(key): {
"url": string,0
"width": unsigned integer,
"height": unsigned integer
}
}
The order parameter should allow you to order them by title you cant change the parameter it uses to sort on.
buildApiRequest('GET',
'/youtube/v3/subscriptions',
{'part': 'subscriberSnippet',
'myRecentSubscribers': 'true',
'order', 'alphabetical'});
Response
{
"kind": "youtube#subscriptionListResponse",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/wLsZnuAVb0T9-bdRdCnreaWBHNM\"",
"nextPageToken": "CAUQAA",
"pageInfo": {
"totalResults": 7,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#subscription",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/3_huGriwUWV4fbbzcclmEoNYJ3w\"",
"id": "moP_YQe1scKJgrI0udrz3B2tJTmRwvz4ev3R2_L4JmI",
"subscriberSnippet": {
"title": "Kortney W",
"description": "",
"channelId": "UC33FFHTxOZ6NRZAp9afsRBw",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/-T6Sn1ur07bk/AAAAAAAAAAI/AAAAAAAAAAA/BSSSRckoD4k/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"medium": {
"url": "https://yt3.ggpht.com/-T6Sn1ur07bk/AAAAAAAAAAI/AAAAAAAAAAA/BSSSRckoD4k/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"high": {
"url": "https://yt3.ggpht.com/-T6Sn1ur07bk/AAAAAAAAAAI/AAAAAAAAAAA/BSSSRckoD4k/s800-c-k-no-mo-rj-c0xffffff/photo.jpg"
}
}
}
},
{
"kind": "youtube#subscription",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/UVJds9Q4d24quS-sEG8Qw_3MBzU\"",
"id": "gI5QI3teCs8unbR7__8oVg7KlRfOtWQYR70kXNkS4PY",
"subscriberSnippet": {
"title": "TheCorty",
"description": "",
"channelId": "UC-0O3PZ0VPNySP2bNFAPDIA",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/-8C6KXmEqDho/AAAAAAAAAAI/AAAAAAAAAAA/1roVNa2yF0o/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"medium": {
"url": "https://yt3.ggpht.com/-8C6KXmEqDho/AAAAAAAAAAI/AAAAAAAAAAA/1roVNa2yF0o/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"high": {
"url": "https://yt3.ggpht.com/-8C6KXmEqDho/AAAAAAAAAAI/AAAAAAAAAAA/1roVNa2yF0o/s800-c-k-no-mo-rj-c0xffffff/photo.jpg"
}
}
}
}
]
}
this is only going to work if you own the channel
it does not return all of your subscribers just the most recent.
There is no date in the response you cant sort by date.
you can test this here just make sure you authenticate to the correct channel

Modifying Embers expected json api response

I'm new to Ember and from what I understand it has a very specific way it excepts its json api response to look like. Like so:
{
"post": {
"id": 1,
"title": "Node is not omakase",
"comments": [1, 2, 3]
},
"comments": [{
"id": 1,
"body": "But is it _lightweight_ omakase?"
},
{
"id": 2,
"body": "I for one welcome our new omakase overlords"
},
{
"id": 3,
"body": "Put me on the fast track to a delicious dinner"
}]
}
Now the api I've already built has an json response that looks like so:
{
"data": {
"id": 1,
"name": "Pansy Bednar",
"links": [
{
"rel": "self",
"uri": "/pansy-bednar15"
}
],
"players": {
"data": [
{
"id": 2,
"name": "Nicholas O'Reilly",
"position": "cad",
"age": 23,
"value": "640",
"links": [
{
"rel": "self",
"uri": "/team/nicholas-o-reilly71"
}
]
}
]
}
}
}
The api is pretty big and is working fine with the mobile app. So a code re write would be to costly I would just choose another js framework even though I like Ember the best.
So my question is is there any way I can adapt the expected json response in ember. If yes how hard is it? Worth the time or should I just go for Angular or Aurelia.
or am I completely wrong and there is no one expected response to ember?
The thing you can do with ember is to write your very own adapter for this there are already many questions+answers out there:
https://stackoverflow.com/a/17938593/1581725
https://stackoverflow.com/a/24411550/1581725
...
And there is also this blog entry here: http://eviltrout.com/2013/03/23/ember-without-data.html it's about using ember without ember-data.
Found this little gem called normalizePayload - maybe this would also work for your case: https://stackoverflow.com/a/21790093/1581725

Iterate through nested Javascript Objects from API response

I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);

Categories