How do I refer to this JSON Object Data? - javascript

I want to reference my Strapi database to my Next.JS Frontend. How can I reference a JSON data if it is also an object within the object?
As an example, to access the name, I use {activity.name}. How can I access the providerName?
I tried {activity.provider.providerName} but it is not working. What am I doing wrong?
[
{
"id": 1,
"name": "Bowling in Mundsburg",
"activityType": "Bowling",
"profileType": "Basic",
"adventureType": "Activity",
"slug": "bowling-in-new-york",
"provider": {
"id": 1,
"providerName": "Bowlingcenter New York",
"slug": "bowlingcenter-new-york",
"published_at": "2021-09-26T12:06:12.670Z",
"created_at": "2021-09-26T12:04:28.585Z",
"updated_at": "2021-09-26T12:06:12.690Z"
},
...
]

could you try like so?
const strapiRes = [
{
"id": 1,
"name": "Bowling in Mundsburg",
"activityType": "Bowling",
"profileType": "Basic",
"adventureType": "Activity",
"slug": "bowling-in-new-york",
"provider": {
"id": 1,
"providerName": "Bowlingcenter New York",
"slug": "bowlingcenter-new-york",
"published_at": "2021-09-26T12:06:12.670Z",
"created_at": "2021-09-26T12:04:28.585Z",
"updated_at": "2021-09-26T12:06:12.690Z"
}
}
];
const whatYouAreAskingFor = strapiRes[0].provider.providerName
also if you are looping try something like:
strapiRes.map(activity => activity.provider.providerName)

Related

Postman - Looping through an array of nested objects to make a variable

I am trying to set a variable from following phone number with value: “+33652556777” (index 4 in JSON attached below) which is the last object in contacts (index 4).
To do so is pretty simple:
let jsonData = pm.response.json();
console.log (jsonData.contacts[4].phone_numbers[0].value)
const PhoneNumber = jsonData.contacts[4].phone_numbers[0].value
pm.environment.set("Jacky", PhoneNumber);
Since I have to use different query parameters to filter by eg. created_at=asc, desc, the property of the phone_numbers order might change index number and I won’t be able to fetch desire phone number "+33652556777” instead it will set a different phone number which I cannot allow.
I know there is way to fetch our number and make it variable for next requests, which is iterating over properties or keys in the object “ for….in or for…of ” but for some reason I cannot achieve it.
What I could achieve is to get through first object “contacts” but impossible to get to its nested array “phone_numbers”. Here is how I did it:
let jsonData = pm.response.json();
let contact;
for (let filter of jsonData.contacts){
if (filter.last_name == "Rowland"){
contact = filter;
}}
console.log (contact);
Could you please help?
Here goes the JSON body response:
{
"contacts": [
{
"id": 11121211,
"direct_link": "https://example.example",
"first_name": "test1",
"last_name": "test",
"company_name": "test",
"information": null,
"is_shared": true,
"created_at": 1582798926,
"updated_at": 1582798926,
"emails": [],
"phone_numbers": [
{
"id": 60065270,
"label": "Work",
"value": "+33134567666"
}
]
},
{
"id": 22222222,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686067,
"updated_at": 1583686067,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567899"
}
]
},
{
"id": 33333564,
"direct_link": "https://example.example",
"first_name": "Jessica",
"last_name": "Biel",
"company_name": "N-Sync",
"information": null,
"is_shared": true,
"created_at": 1583686086,
"updated_at": 1583686086,
"emails": [],
"phone_numbers": []
},
{
"id": 45678901,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686105,
"updated_at": 1583686105,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567333"
}
]
},
{
"id": 56789123,
"direct_link": "https://example.example",
"first_name": "Jacky",
"last_name": "Rowland",
"company_name": "Test Company1",
"information": "",
"is_shared": true,
"created_at": 1583745888,
"updated_at": 1608556499,
"emails": [
{
"id": 76594398,
"label": "Work",
"value": "mandatory_field#example.com"
}
],
"phone_numbers": [
{
"id": 60650277,
"label": "Mobile",
"value": "+33652556777"
}
]
}
],
"meta": {
"count": 6,
"total": 241,
"current_page": 1,
"per_page": 5,
"next_page_link": "https://example.example",
"previous_page_link": null
}
}
You could use something basic like this:
_.each(pm.response.json().contacts, (contact) => {
if(contact.last_name === "Rowland") {
pm.environment.set(`${contact.first_name}_${contact.last_name}_number`, contact.phone_numbers[0].value)
}
})
There are probably better and more performant ways to do this but if you just want to set a variable for that contact, no matter where they are in the response - This would work :D
you can use forEach or _.each as danny mentioned to get all numbers else use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers[0].value)
use array.find to find the contact with first_name jacky adn then get phone_number[0].value from it.
if you want all numbers from that array then use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers.map((a)=>a.value))
here we map the result to get only the numbers from phone_number array.
is it what you looking for !?

accessing a json child object not in an array

I'm trying to accessing a json child object which is not in an array. i've tried accessing it with my below script but its not working. i want to be able to access the menuCategory Object
JSON
[
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
]
JAVASCRIPT
callEditMenu(parent, content) {
this.modalService.open(content);
this.editMenuCategoryId = parent.menuCategory.id;
}
May be like
const parent = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
console.log(parent[0].menuCategory.id);
If the parent argument in the callEditMenu function is referring to the JSON you included then try parent[0].menuCategory.id
let arr = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
for (let item of arr) {
if (item.hasOwnProperty("menuCategory")) {
console.log(item["menuCategory"]);
}
};
let res = arr.filter((item) => item && item.menuCategory);
console.log(res[0].menuCategory);
In case you need to find it dynamically. Above are two different ways
Considering there would be multiple items in your array of objects, you can iterate through each object to get the menuCategory name as
let obj = [
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
];
obj.forEach(elem => {
console.log(elem.menuCategory.name);
});

Search Similar value in json [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
when i am using fetch i am getting data in json format. I want to search json via cust_id and return only matching record. please tell me how to do it. I have to show all the credit card the person have.
"objects": [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
var objects= [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
console.log(objects.filter(i=>i['cust_id'] === '12345'))
I hope it helps
var val={
"objects": [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
};
function get(val,custid){
var result;
for(var i=0;i<val.objects.length;i++){
if(val.objects[i].cust_id=custid){
result= val.objects[i];
}
}
return result;
}
console.log(get(val,"1235"));
For multiple records you can take result as array and use array.push to insert in result (function variable) and return the array in end

Checking a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

How to render or populate data coming from websocket services like pusher using angularjs ngRepeat?

I am new to realtime application and its bothering for a while how to render the data coming from websocket services like pusher using the angularjs ngRepeat directive..
below are the response from the api
and the snippets code i have.
Client Side.
$scope.exam_results = [{}];
var client = new Pusher('some_key');
var pusher = $pusher(client);
var my_channel = pusher.subscribe('some_channel');
my_channel.bind('some_event', function(data) {
$scope.some_var = data;
console.log($scope.some_var);
});
Server Side
.....
LaravelPusher::trigger($some_channel, 'some_event', $some_var);
By the way im using laravel and angularjs.
Need little help here guys.. thank you ^_^
Api Response
[
{
"id": 1,
"subject_id": 1,
"student_id": 1,
"correct": 0,
"incorrect": 30,
"created_at": "2016-02-17 17:47:36",
"updated_at": "-0001-11-30 00:00:00",
"exam_taken": 1,
"students": {
"id": 1,
"firstname": "Mary Rose",
"lastname": "Labrador",
"middlename": "Neneng",
"birthdate": "2016-02-10",
"email": "maryrose#dummy.com",
"username": "maryrose",
"gender": "Female",
"password": "65ce8ebfe1687cb8a5460fab48bcea413a0e17f53636912ac4667f056eeca461",
"guardianname": "Unnamed",
"guardiancontact": "+6309083561578",
"personalcontact": "+6309083561578",
"department_id": 1,
"taken_exam": 1,
"created_at": "2016-02-16 00:00:00",
"updated_at": "2016-02-17 17:47:58"
},
"subjects": {
"id": 1,
"subjectname": "Algorithm",
"slug": "algorithm",
"time": "10:00:00",
"schedule": "MWF",
"teacher_id": 1,
"created_at": "2016-02-12 09:28:27",
"updated_at": "2016-02-12 09:28:27"
}
},
{
"id": 2,
"subject_id": 1,
"student_id": 4,
"correct": 0,
"incorrect": 30,
"created_at": "2016-02-17 18:54:11",
"updated_at": "-0001-11-30 00:00:00",
"exam_taken": 1,
"students": {
"id": 4,
"firstname": "Joan Phylis",
"lastname": "Rogano",
"middlename": "Latoja",
"birthdate": "2016-02-14",
"email": "joangwapa#dummy.com",
"username": "joan143",
"gender": "Female",
"password": "65ce8ebfe1687cb8a5460fab48bcea413a0e17f53636912ac4667f056eeca461",
"guardianname": "Unnamed",
"guardiancontact": "+639083561578",
"personalcontact": "+639083561578",
"department_id": 1,
"taken_exam": 1,
"created_at": "2016-02-16 00:00:00",
"updated_at": "2016-02-17 18:57:43"
},
"subjects": {
"id": 1,
"subjectname": "Algorithm",
"slug": "algorithm",
"time": "10:00:00",
"schedule": "MWF",
"teacher_id": 1,
"created_at": "2016-02-12 09:28:27",
"updated_at": "2016-02-12 09:28:27"
}
}
]
HTML
<tr ng-reapeat="result in exam_results track by $index">
<td>
<span class="text-success">#{{result.students.lastname}},
#{{result.students.firstname}} #{{result.students.middlename}}
</span>
</td>
<td> View</td>
</tr>
As $scope.exam_results is an array, why not just use Array.concat() to add the new data to it? Angular's digest cycle would then render it:
$scope.exam_results = [];
// your websocket code
my_channel.bind('some_event', function(data) {
$scope.exam_results.concat(data);
console.log($scope.exam_results);
});
Obviously, the data from the websocket needs to be the same format over time and also an array of objects. You would bind your ng-repeat to $scope.exam_results.
<ul>
<li ng-repeat="result in exam_results track by $index">
{{result.students.firstname}}
</li>
</ul>
If your event data is consistently going to be an Array of Objects.
You can do something like this -
$scope.exam_results = []; // Changed this to Array.
var client = new Pusher('some_key');
var pusher = $pusher(client);
var my_channel = pusher.subscribe('some_channel');
my_channel.bind('some_event', function(data) {
$scope.exam_results.concat(data) // Concatinating Array to merge with existing Results.
});
Now you can have your view something like this -
<div ng-repeat="result in exam_results">
<!-- HTML to render Result -->
<span>{{result.students.first_name}}</span>
</div>
Hope this helps.

Categories