i have a api with peoples i am tring to dispaly names of people
"peoples": [
{
"id": 2,
"mainModule": "bonding",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "hari",
"completed": false
},
{
"id": 4,
"name": "meenu",
"completed": false
}
]
"id": 1,
"mainModule": "bonding2",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "jisa",
"completed": false
},
{
"id": 4,
"name": "stepy",
"completed": false
}
]
},
]
This is my data in api
I am using axios to set a state called items
axios
.get(
"url",
config
)
.then((res) => {
console.log(res.data.peoples)//this works
console.log(res.data.peoples.persons);//here i am getting error
this.setState({ items: res.data.peoples.persons}); error
}
I am trying to pass persons so I can map person names in JSX
i have changed the code pls help
Welcome to StackOverflow! As you can see in your first snippet you have an array inside peoples so the correct way to access it would be:
res.data.peoples[0].persons
Hope this solves your problem. You can read more about it in MDN docs
edit:
If you would like to iterate over persons you can do this:
res.data.peoples.map(person => (
<div key={person.id}>{person.name}</div>
));
Remember you must pass a unique key prop to the component so React can create and mantain the list correctly. More info about it in the Docs.
res.data.peoples is an array so you should iterate over it. It doesn't have persons property, it has [0], [1] etc. Try to log res.data.peoples[0].persons
From the sample data you showed, peoples is an array. So to access persons, you should be able to access it using the following, for example if you want to access the first element of the array:
res.data.peoples[0].persons
Otherwise, if you want to access it as res.data.peoples.persons then you have to change your API output such that it is like so :
"peoples": {
"id": 2,
"mainModule": "bonding",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "hari",
"completed": false
},
{
"id": 4,
"name": "meenu",
"completed": false
}
]
}
Related
Please, help me. I cant find information about how do this.
I have got this code. It load all products with all relations. One of relations is product item. In product item entity I have got price column.
How I can get minimal product item price without get in my response array of product items?
const { skip, take } = pagination;
const query = this.createQueryBuilder('product');
query.where('product.shop = :id AND product.blocked = FALSE', {
id: shop.id,
});
if (skip) {
query.offset(Number(skip));
}
if (take) {
query.limit(Number(take));
}
query.leftJoin('product.info', 'info');
query.leftJoin('product.avatar', 'avatar');
// load product items
query.leftJoin('product.productItem', 'item');
query.select([
'product.id',
'product.path',
'info.name',
'info.description',
'info.info',
'info.lang',
'avatar.path',
'avatar.type',
'item.price'
]);
const [list, amount] = await query.getManyAndCount();
Now i have got:
{
"list": [
{
"id": 3,
"path": "admin-product-2",
"order": 1,
"shop": {
"id": 1
},
"info": [
{
"name": "Admin Name ;)",
"description": "Shorty",
"info": "",
"lang": "RU"
}
],
"avatar": null,
"productItem": [
{
"price": 1000
},
{
"price": 500
},
{
"price": 300
},
{
"price": 2000
},
{
"price": 3000
}
]
}
]
}
........
But I need:
{
"list": [
{
"id": 3,
"path": "admin-product-2",
"order": 1,
"shop": {
"id": 1
},
"info": [
{
"name": "Admin Name ;)",
"description": "Shorty",
"info": "",
"lang": "RU"
}
],
"avatar": null,
"minProductItemPrice": 300
}
]
}
Pls help me
You can find the answer for this on Stackoverflow already.
Here is a similar question Typeorm select max with specific column
Basically, getManyAndCount() method that you are using is useful when fetching entities. In your case, you are trying to obtain an aggregate value encompassing multiple entities.
You need to make separate selection, like so
query.select("MIN(item.price)", "min");
and then get the result with
return query.getRawOne();
I have an array which looks like this:
[
{
"boxes": [
{
"id": 2,
"content": {
"name": "ABC",
"details": "some details for abc"
}
}
]
},
{
"boxes": [
{
"id": 3,
"content": {
"name": "XYZ",
"details": "some details for xyz"
}
},
{
"id": 4,
"content": {
"name": "UVW",
"details": "some details for uvw"
}
}
]
},
{}
]
And I have a variable: let id = 3
I want to be able to search through the nested array "boxes" to find the content property of the object that have the given id. Such that the result is:
{
"name": "XYZ",
"details": "some details for xyz"
}
Till now I have gathered that I can use a combination forEach and .filter do find this. But I'm not sure how. Also, I have control over the original data. So, if there's a better way to store the original data, I will be glad to have suggestions.
Actually I did attempt but got stuck:
Let's say the original array is called house.
let matches = []
let id = 3
house.forEach(function(e) {
matches = matches.concat(e.boxes.filter(function(b) {
return (b.id === id);
}));})
console.log(matches[0].content)
You could use map method by passing a callback function as argument. The scope of map method is to get all items from boxes array.
Also, I'm using filter(Boolean) statement in order to remove undefined value for those items which doesn't have boxes as property.
At least, use find method in order to get the desired output result.
let arr = [ { "boxes": [ { "id": 2, "content": { "name": "ABC", "details": "some details for abc" } } ] }, { "boxes": [ { "id": 3, "content": { "name": "XYZ", "details": "some details for xyz" } }, { "id": 4, "content": { "name": "UVW", "details": "some details for uvw" } } ] }, {} ]
let id = 1;
let result = [].concat(...arr.map(item => item.boxes))
.filter(Boolean)
.find(({id}) => id == id).content;
console.log(result);
First you need to put boxes object into one array, it seems it just has couple extra levels you don't need; You can create a helper function for that.
make a loop with if statement if there is what you are looking for or not
Here I use forEach() to loop through the data and get the boxes.
After that, I use filter() to get the object with the desired id. That's all.
const data = [
{
"boxes": [
{
"id": 2,
"content": {
"name": "ABC",
"details": "some details for abc"
}
}
]
},
{
"boxes": [
{
"id": 3,
"content": {
"name": "XYZ",
"details": "some details for xyz"
}
},
{
"id": 4,
"content": {
"name": "UVW",
"details": "some details for uvw"
}
}
]
},
{}
]
data.forEach(data => {
if (data.boxes){
let searchedData = data.boxes.filter(box => box.id == 3);
if (searchedData.length > 0){
console.log(searchedData[0].content);
}
}
});
This question already has answers here:
How to get names of enum entries?
(43 answers)
Closed 4 years ago.
I have an enum file where I have defined an object for PaymentTypes:
export enum PaymentTypes {
Invoice = 1,
CreditCard = 2,
PrePayment = 3,
}
Now, when I receive data as an array from my database I also receive the PaymentType as a number:
order:
[
{ "id": 0, "name": "Available", "PaymentType": 1 },
{ "id": 1, "name": "Ready", "PaymentType": 3 },
{ "id": 2, "name": "Started", "PaymentType": 2 }
];
Now my question is, how can I filter out each payment type in the array and convert the number to the string that's defined in the enum file so that I can us this data to display it to the user in the front end?
So that I have something like this that I can work with:
orderFiltered:
[
{ "id": 0, "name": "Available", "PaymentType": "Invoice" },
{ "id": 1, "name": "Ready", "PaymentType": "PrePayment" },
{ "id": 2, "name": "Started", "PaymentType": "CreditCard" }
];
You can use map to create a new array of objects that contains the original data and the name of the enum member, which you can get using PaymentTypes[PaymentType]
let order = [
{ "id": 0, "name": "Available", "PaymentType": 1 },
{ "id": 1, "name": "Ready", "PaymentType": 3 },
{ "id": 2, "name": "Started", "PaymentType": 2 }
];
enum PaymentTypes {
Invoice = 1,
CreditCard = 2,
PrePayment = 3,
}
let orderFiltered = order.map(o => Object.assign({}, o, { PaymentTypeDisplayName: PaymentTypes[o.PaymentType] }));
console.log(orderFiltered);
One thing to note though is that using the enum member name as a display might not be the friendliest of use experiences.
Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator
In a collection i need to set the value to one of attributes, but i cant find the way how do it
products.models[i].set({'category.name':'some_value'})
the rest api looks like this
{
"category": {
"id": 3,
"name": "Drink",
"icon": "staging/main/category/icon-drinks.png"
},
"id": 1,
"name": "Sugar54",
"dashboard": 1,
"last_buy": "2013-10-02",
"price": "102",
"buy_period": 7
},
How do i do that ?
If you have complex nested models, I suggest you take a look at BackboneRelational.
Otherwise in your case, you should be fine with
products.models[i].get('category').name = 'some_value';
supposing that category is a normal object.