I have an app where the user will search for a term and they will see the results rendered. The results, in this case, are from a nested JSON object. I have a component called CompanyInfoList that passes props to Results component that renders the JSX. The props are employee, date, tax, and balance. I tried to map within a map in the component, but it did not work. My goal is to get access to the details data, how do I do this. The files to look at are CompanyInfoList and Results. The data is loaded in via axios in CompListContext
In the CompSearch comp when you enter "ABC" nothing will happen, because I am not accessing the details data from the JSON obj. This is what I need help in doing.
Here is the mongo DB JSON object (pasted from PostMan):
"data": {
"details": {
"employee": "person1",
"date": "test date",
"tax": "test tax",
"balance": "22"
},
"company": "TEST-ABC",
"_id": "60dba9fe7641a44d40364c1f",
"__v": 0
}
Here is my code
Given the company array object shape:
{
details: {
employee: "person1",
date: "test date",
tax: "test tax",
balance: "22"
},
company: "TEST-ABC",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
}
You are filtering by the element's company property, and when mapping the filtered results in CompanyInfoList you need to access the details property, i.e. result.details.employee.
const CompanyInfoList = ({ filtered }) => {
const fltr = filtered.map((result) => (
<Results
key={result.details.id}
employee={result.details.employee}
date={result.details.date}
tax={result.details.tax}
balance={result.details.balance}
/>
));
return <>{fltr}</>;
};
Related
so I try to fetch data from my MongoDB collection using mongoose and typescript.
I can successfuly get fetched data but the problem I have is, that I can only access _id, season and avatar with syntax like {{response.season}} or {{response.avatar}}. Nested data inside avatar JSON object can be accessed only like it's dictionary {{response.avatar["transfer"]}} and I'm not sure why is that. I would like to access it like {{response.avatar.transfer}}, is it possible to do that ?
Fetching data from MongoDB using mongoose
export default async function run() {
// 4. Connect to MongoDB
await mongoose.connect(config.publicRuntimeConfig.MONGO_URI);
const results = await User.findOne({
'season': '123'
})
await mongoose.disconnect();
return results
}
Data I receive
{
"_id": "630fbca3d06e5e2f310ea540",
"season": 123,
"avatar": {
"from_team_id": 1,
"to_team_id": 2,
"transfer": "asdasd",
"type": "dasdasd",
"date": "asdasd",
"amount": "asdasd",
"player": {
"player_id": 12,
"country_id": 412,
"display_name": "asdasd",
"nationality": "asdasd",
"_id": "630fbca3d06e5e2f310ea542"
},
"_id": "630fbca3d06e5e2f310ea541"
},
"__v": 0
}
I want to access data like this if it's possible
<template v-for="transfer in transferData">
{{transfer.avatar.amount}}
</template>
What I can do now is
<template v-for="transfer in transferData">
{{transfer.avatar["amount"]}}
</template>
Is it possible to do that?
You can access all of the response objects properties by defining a type or interface and setting the response object as that type. I'd recommend defining a type for your avatar and player object and then one for the entire response that contains the avatar type you defined.
type response = {
"_id”:string;
avatar:Avatar
// The rest of your properties
}
type avatar = {
“from_team_id”:string;
player:Player;
// Rest of properties
}
iam currently developing a contact management system web app using ember js for the front end .Iam using ember store for fetching the data from the api , while fetching json data using store.findAll() , iam getting the json array with the length of data as expected but when i try to access the data at a specific position in the json array it gives undefined value , it is not giving the model value.I have checked everything like json format , naming conventions with respect to my serializer but cant able to find what is going wrong , can anyone help me with solving this ?
Application adapter :
import RESTAdapter from '#ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
buildURL(...args) {
return "http://localhost:8082/ContactManagementSystem1/api/contact/5";
}
headers = {
'Accept': '*/*',
};
}
Json response from api :
[
{
"firstName": "Example",
"lastName": "K",
"deletedAt": "",
"mobileNumberHome": "7827382738",
"companyName": "Example",
"dateOfBirth": "2000-04-12",
"id": 21,
"userId": 4,
"mobileNumberWork": "2738273788",
"email": "rath#gmail.com"
},
{
"firstName": "nameexample2",
"lastName": "p",
"deletedAt": "",
"mobileNumberHome": "8989898996",
"companyName": "Business ",
"imageURL": "actress1.jfif",
"dateOfBirth": "2021-10-05",
"id": 51,
"userId": 4,
"mobileNumberWork": "8667889896",
"email": "nameexample2h#gmail.com"
}
]
Serializer :
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeResponse(store, primaryModelClass,payload,id,requestType){
arguments[2] = {
"contacts" : payload
}
return this._super(...arguments);
}
});
Since my json response is different from the RestSerializer format i have written some code in the serializer for normalising the response.
Route where i fetch data using store.findAll()
import Route from '#ember/routing/route';
import {inject as Service } from '#ember/service';
export default class UserContactRoute extends Route {
#Service store;
async model() {
return this.store.findAll('contact');
}
}
These are codes which i have used , i have also checked in the inspect's console no error is been thrown , the problem is model array object were undefined.
One should use the objectAt(index) for accessing array elements because those arrays are not regular JS ones. See here:
It's important to note that RecordArray is not a JavaScript array,
it's an object that implements MutableArray. This is important
because, for example, if you want to retrieve records by index, the []
notation will not work--you'll have to use objectAt(index) instead.
I am very new to Postman and have a method in my API taking in 2 params: AccountNumber and GroupId to check if there's a customer Id associated with the AccountNumber. When I run the Post request, if it returns 2 or more customerIds, I'm supposed to return the response to the user to pick which customerId to use. How do I do that?
Right now, in the body of the request, I have:
{
"AccountNumber":"0001",
"GroupId": "1"
}
The output is an array of customerId. How do I test with only one customerId picked from the POST response?
Thank you for your help, I really appreciate it!
It's unlikely to be a Postman issue.
You are consuming the API through Postman. You are not able to control the output of the API itself from Postman.
What you can do, though, is write a test case for the current request. There is a 'Tests' tab, where the 'Params' tab is. At the right, there are snippets on how to create the test with response body. Let me give you a simple test case to get the first element:
Let's say I have the following response body
[
{
"name": "Blue",
"id": "5f1830d217afbb52acac9868"
},
{
"name": "Orange",
"id": "5f1e7afeb334ae70b4f05d1d"
},
{
"name": "Red",
"id": "5f1e7b10b334ae70b4f05d1e"
},
{
"name": "Green",
"id": "5f1e7b10b334ae70b4f05d1f"
},
{
"name": "Yellow",
"id": "5f1e7b10b334ae70b4f05d20"
}
]
The test case would look like this:
pm.test("Example Test", function () {
var jsonData = pm.response.json();
pm.expect(jsonData[0]).to.eql({
name: "Blue",
id: "5f1830d217afbb52acac9868"
});
});
The json data is in the below pattern. And the Json data is coming from backend and getting through api and storing in a state variable.
{
"message": "user created successfully",
"status": "success",
"student": {
"class": "10",
"email": "user#gmail.com",
"name": "User",
"password": "user",
"phone_number": "some phone number",
"school": "1",
"section": "a"
}
}
I have stored the data which is returned through api in a state variable.
constructor(){
super();
this.state = {
jsonData: ''
}
}
And tried accessing using below fashion.
this.state.jsonData.status
but not able to access. How can I access the status value in react?
Please check type of jsonData in state when you call it using typeof or instanceof.
It maybe by you store fetched data in string type without check and manipulating.
If it is string type, convert it using JSON.parse
I am new to Ember and JSON. I want to parse a JSON object that is below with typeahead library
and access nested object values by searching their keys.
I have this Json format:
return [
{
"id": 1,
"category_name": "Supermarket",
"category_description": "SUPER MARKET",
"image_url": "",
"merchants": [
{
"name": "CARREFOUR",
"id": 12,
"merchant_type_id": 1,
"merchant_type_description": "Gold",
"merchant_redeption_rate": 0.002500,
"image_url": "https://jpg",
"branches": [
{
"id": 123456,
"latitude": 37.939483,
"area": "ΑΓ. ΔΗΜΗΤΡΙΟΣ",
"zip": "12345"
},
{
"id": 4567890,
"longitude": 23.650622,
"area": "ΑΓ. ΙΩΑΝΝΗΣ ΡΕΝΤΗΣ",
"zip": "12345"
}
]
},
{
"name": "CAFCO",
"id": 13,
"merchant_type_id": 3,
"merchant_type_description": "None",
"merchant_redeption_rate": 0.002500,
"image_url": "https:.jpg",
"branches": [
{
"id": 127890,
"latitude": 38.027870,
"area": "ΠΕΡΙΣΤΕΡΙ",
"zip": "12345"
}
]
}
]
},
{
"id": 2,
"category_name": "Πολυκαταστήματα",
"category_description": "ΠΟΛΥΚΑΤΑΣΤΗΜΑ",
"image_url": "",
"merchants": [
{
"name": "AGGELOPOYLOS CHR.",
"id": 15,
"merchant_type_id": 2,
"merchant_type_description": "Silver",
"merchant_redeption_rate": 0.002500,
"image_url": "https://www.nbg.gr/greek/retail/cards/reward-programmes/gonational/PublishingImages/aggelopoulos.jpg",
"branches": [
{
"id": 234780,
"latitude": 35.366118,
"longitude": 24.479461,
"address": "ΕΘΝ. ΜΑΚΑΡΙΟΥ 9 & ΕΛ. ΒΕΝΙΖΕΛΟΥ 1",
"area": "Ν. ΦΑΛΗΡΟ",
"zip": "12345"
}
]
}
]
}
];
--------------------------Updated----------------------------
For example, i want to search using typeahead the name of merchants and when the letter we write to search matches the name of merchants it will appear the corresponding category_name and backwards.
Example -> when i keyboard the s it will appear :
Category : Supermarket,
Name: CARREFOUR
Name: CAFCO
And the same output on the dropdown of search when i keyboard the letter c.
Any help?
New Jsbin example
The simplest way (in my mind) to get this to work is to create a computed property that will contain an array of latitudes. But how do we get there?
To get to latitude, you need to go through array of merchants and then array of branches. Being that this will be across multiple elements, you are going to end up with "array of arrays" type data structure, which is annoying to deal with. So, to simplify this, we can create a simple flatten function as follows:
flatten: function(origArray){
var newArr = [];
origArray.forEach(function(el) {
el.forEach(function(eachEl){
newArr.push(eachEl);
});
});
return newArr;
},
In addition to our function above, Ember already provides us with many other useful functions that can be used on arrays (see here). One of those is mapBy(property) which transforms an array into another array only keeping the values of the property we specified.
So, to create a lats (for latitudes) property, we can just do this:
lats: function(){
var merchantsArr = this.get('model').mapBy('merchants');
merchantsArr = this.flatten(merchantsArr);
var branchesArr = merchantsArr.mapBy('branches');
branchesArr = this.flatten(branchesArr);
return branchesArr.mapBy("latitude").compact();
}.property('model')
Above, I am basically using mapBy, flatten (see above) and compact which
Returns a copy of the array with all null and undefined elements removed.
Once you have the lats property with all the necessary data, the rest is easy.
Your call to component becomes:
{{x-typeahead data=lats name='category_name' selection=myColor}}
Note lats instead of model you originally were passing into the component.
And now, to access the value of data property in the component, you do
`this.get('data')`
which you can just pass in as the source like so:
source: substringMatcher(self.get('data'))
Working solution here
Update
Updating my answer based on your updated question.
OK, so this is getting a little more complicated. You now need more than just one property (latitude) from the object. You need category_name and merchant name.
In addition to mapBy, which just grabs one property out of array, Ember also has map which lets you transform the array into pretty much anything you want to:
lats: function(){
var merchantsArr = this.get('model').map(function(thing){
var category_name = thing.category_name;
return thing.merchants.map(function(merchant){
return {
"name": merchant.name,
"category": category_name
};
});
});
merchantsArr = this.flatten(merchantsArr);
return merchantsArr;
}.property('model')
The code above looks complicated, but it's basically just returning an array of top level objects' merchants accompanied by category_name. Since this is an array of arrays, we will need to flatten it.
Then, inside the component, we need to keep in mind that we are not just passing in an array of strings, but rather we are passing in an array of objects. Therefore, we need to look through object's properties (name and category) for a match
$.each(strs, function(i, str) {
if (substrRegex.test(str.name) || substrRegex.test(str.category)) {
matches.push(str);
}
});
Lastly, to actually display both category and merchant name, you need to tell Typeahead how to do that:
templates: {
suggestion: Handlebars.compile('<p>{{name}} – {{category}}</p>')
}
Working solution here