I find a new problem,
I would like to count #NAME to set array FACET[] for show #KEY
Myjson
" RESULT":{
"FACET":[
{ "#NAME" : "creator",
"#COUNT" : "20",
"FACET_VALUES":[
{
"#KEY":"Book Company1",
"#VALUE":"13"},
{
"#KEY":"Book Company1์",
"#VALUE":"10"}],
{ "#NAME" : "lang",
"#COUNT" : "70",
"FACET_VALUES":[
{
"#KEY":"tha",
"#VALUE":"33"},
{
"#KEY":"eng",
"#VALUE":"42"}
],
{ "#NAME" : "bnb",
"#COUNT" : "64",
"FACET_VALUES":[
{
.
.
.
]
.
optionsFn(): void {
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
console.log(this.date);
console.log(this.date);
this.goToapply()
}
goToapply(){
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos=data.json().RESULT.FACET[0,1,2,3.4......].FACET_VALUES; ///get #KEY
},error=>{
console.log(error);
} );
}
..
<ion-label>Filterr</ion-label>
<ion-select [(ngModel)]="refine" (ionChange)="optionsFn();">
<ion-option value="..." *ngFor="let item of date">{{item["#NAME"]}},({{item["#COUNT"]}})</ion-option>
</ion-select>
<ion-list>
<ion-item *ngFor="let item of foundRepos" (click)="itemClicked($event,item)">
<h3> {{ item[#KEY"] }}</h3>
</ion-item>
</ion-list>
This value="..." I want to keep it to string for to use, but zi have know idea.
example : count #NAME = 3 (creator,lang,bnb) ,and get value="..." = 0,1,2 (0==creator ,1==lang ,2==bnb)
When I select lang I get 1 , I use this to FACET[1].FACET_VALUES , So that I get #KEY
Sorry to write wrong. My english isn't very good.
Ok. there's just a tip that I would like to point out to you. You shoud get a bit better with words. Not the English language in particular but more about explaining your current result and your desired result. I believe this will force you into learning english at a much faster pace than you're currently doing. (coming from a non-native speaker)
"I would like to count#NAME to set array FACET[] for show #KEY"
So, with the returned JSON we can do a couple of things, which do not get quite clear from immediately looking at your question (did a +1 since I don't believe it's of bad quality or isn't a good question).
So there are 3 things I should cover in my post
Counting the amount that NAME occurs
Setting an array for the FACET
Showing the KEY per FACET which seems to be the end goal.
Ok
Counting the amount that NAME occurs
So you basically already got this answer. You submitted this code
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
});
Which means you already have access to the FACET array. Counting the amount that NAME occurs can be done either by creating a for loop and checking if the name is not undefined (thus incrementing an int) or counting on the fact that NAME is always defined, thus just calling this.date.size() (if this.date is set correctly of course)
get an array for the FACET
this, you're already doing by assiging the this.date = data.json().RESULT.FACET. Your this.date now contains an array holding your FACET objects. Just see it like this: JSON (with comments which is not possible in JSON but just for demonstration purposes) =
{ FACET: // declare the main object, called FACET
[ // declaring the FACET as an Array ([] is for creating a list)
{id: 2} //initializing a child of the FACET array
,{id: 3} //initializing the second FACET child.
]
}
So, this pseudo (not realistic) JSON holds 2 objects, having id = 2 and id = 3
Ok, now you should understand a bit of JSON, let's take a look at how your code looks (taking a Businnes with multiple offices and multiple employees per office into account)
{
OFFICES" : [
{
"id" : "1",
"location" : "New York",
"employees" : [
{"id" : "1", "fullName" : "Jon Skeet"},
{"id" : "2", "fullName" : "Random Stranger"}
]
},
{
"id" : "2",
"location" : "Amsterdam",
"employees" : [
{"id" : "1", "fullName" : "Ivaro18"},
{"id" : "2", "fullName" : "Some-Random Stranger"}
]
}
]
}
This code is basically the same as your code. And the question your asking now is, taking the code from my answer, how to get all the id's or names of all the employees. (get all names of keys of facet objects)
Now let's show you in typescript
someFunction() {
this.http.get('someUrl').map(response => {
console.log(JSON.stringify(response.json())); // check what you actually retrieve
let decoded = response.json();
for(let office of decoded.OFFICE) {
console.log(office.location);
for(let employee of office.employees) {
console.log(employee.fullName);
}
}
});
}
Expected output of this program
> New York
> Jon Skeet
> Random Stranger
> Amsterdam
> Ivaro18
> Some-Random Stranger
I think this pseudo code will get you to think a bit out-of-the-box and find the answer to your question. If you can't elaborate more on what you want as output I will be glad to help you at any time (even weekends) just comment and I'll respond when I have the time!
#Ivaro18 thanks for your answers.
I want to counting the amount that #NAME
for setting an array for the FACET
and showing the KEY per FACET[] which seems to be the end goal.
Yes, you totally know what I meant.
But i want output is every #KEY of that FACET[]
Example :
<ion-select [(ngModel)]="refine" (ionChange)="optionsFn();">
<ion-option value="..." *ngFor="let item of date">{{item["#NAME"]}},({{item["#COUNT"]}})</ion-option>
</ion-select>
<ion-list>
<ion-item *ngFor="let item of foundRepos" (click)="itemClicked($event,item)">
<h3> {{ item[#KEY"] }}</h3>
</ion-item>
</ion-list>
.
optionsFn(): void {
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
console.log(this.date);
console.log(this.date);
this.goToapply()
}
goToapply(){
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos=data.json().RESULT.FACET[0,1,2,3.4......].FACET_VALUES; ///get #KEY
},error=>{
console.log(error);
} );
}
from above ion-select is show creator , lang and bnb ,I want to If When I select lang ion-option value="..."
to keep number of "#NAME"
example counting amount of #NAME is 3 and
when I select creator is ion-option value="..." << is 0
when I select lang is ion-option value="..." << is 1
when I select bnb is ion-option value="..." << is 2
and If i get value ,I take it to goToapply() for set FACET[]
example I select bnb I get value =2 and console.log this.refine
is show 2
take it(2) to let p = this.refine , so that p = 2
take p to this.foundRepos=data.json().RESULT.FACET[p].FACET_VALUES; for show #KEY in ion-list
When I select lang output is
> tha
> eng
Related
I'm trying to filter the json data. There is a field called "brand" in my json (so basically I'm trying to filter the data by brands)
This is how my json looks
{
"items": [
{
"_id": "30baa1ca-4186-4ff0-abe8-a5970e753444",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-09T08:47:29.137Z",
"discountedPrice": "44.97",
"_updatedDate": "2022-05-09T08:48:44.147Z",
"getDealLink": "https://amzn.to/3FqBq4O",
"brands": [
"Amazon"
],
"title": "Mellanni Extra Deep Pocket Twin XL Sheet Set ",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"save": "#1 Best Seller",
"link-items-all": "/items/",
"link-items-title": "/items/mellanni-extra-deep-pocket-twin-xl-sheet-set-"
},
{
"_id": "a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-08T22:35:38.398Z",
"discountedPrice": "$81.59",
"_updatedDate": "2022-05-08T22:39:52.801Z",
"getDealLink": "https://amzn.to/3ymXGLe",
"brands": [
"Amazon"
],
"originalPrice": "$199.99",
"title": "2 Pack Stadium chairs for bleachers with back support",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"link-items-all": "/items/",
"link-items-title": "/items/2-pack-stadium-chairs-for-bleachers-with-back-support"
},
and this is my dart code
void getAmazon() async {
var response = await http.get(Uri.parse(url));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
print(filteredData); // returns nothing
}
it doesn't return/print anything. What am I doing wrong?
Better to use contains to check if a brand is listed. Also check if "brands" field is available for better stability.
final filteredData = data.where((element) => (element['brands'] != null ? element['brands'].contains('Amazon') : false));
In your code, you are checking if brands it's equal to Amazon, but brands is actually a List. (Or in the case you are checking on a particular index, this could change)
So ["Amazon"] ≠ Amazon.
In the code below you will now check if brands contains "Amazon".
Iterable filteredData = data.where((element) => element['brands'].contains('Amazon'));
void getAmazon() async {
var response = await http.get(Uri.parse('https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e'));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
log('ddf ${filteredData}'); // returns nothing
}
I had added third product as brand from flipkart it filter this!
you can check this url https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e
Your code actually works as expected!!!
[log] ddf ({_id: 30baa1ca-4186-4ff0-abe8-a5970e753444, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-09T08:47:29.137Z, discountedPrice: 44.97, _updatedDate: 2022-05-09T08:48:44.147Z, getDealLink: https://amzn.to/3FqBq4O, brands: [Amazon], title: Mellanni Extra Deep Pocket Twin XL Sheet Set , amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, save: #1 Best Seller, link-items-all: /items/, link-items-title: /items/mellanni-extra-deep-pocket-twin-xl-sheet-set-}, {_id: a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-08T22:35:38.398Z, discountedPrice: $81.59, _updatedDate: 2022-05-08T22:39:52.801Z, getDealLink: https://amzn.to/3ymXGLe, brands: [Amazon], originalPrice: $199.99, title: 2 Pack Stadium chairs for bleachers with back support, amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, link-items-all: /items/, link-items-title: /items/2-pack-stadium-chairs-for-bleachers-with-back-support})
I have an array of 5 persons in my json file. Each person has an array with items in it.
In my html code, I'm using *ngFor to loop through the persons to show their name. I also want to show the sum of the prices of the items.
To calculate the prices of their items together, I use a function in my TypeScript code. I'm showing the total of the prices in my console.
The problem is, that the current code I'm using in my typescript file loops through the persons again. So I'm looping through the persons in my html with *ngFor and in this I'm calling the function getTotal(), which loops through the persons again. Of course I want to loop through them only once.
json
"persons":[
{
"name": "Peter",
"items": [
{
"name": "pen",
"price": 1.50
},
{
"name": "paper",
"price": 2.00
}
]
},
{
"name": "Maria",
"items": [
{
"name": "scissors",
"price": 4.00
},
{
"name": "stickers",
"price": 3.00
}
]
}
// three more persons
]
html
<div *ngFor="let person of persons"> <!--here I'm looping through the persons-->
<p>{{person.name}}</p>
<p>Total <span>{{getTotal()}}</span></p> <!--here I'm calling the function, which will loop through persons again-->
</div>
typescript
getTotal() {
for(let person of this.persons){ //here I'm looping through the persons again (what I actually don't want)
let total = 0;
for(let item of person.items){
total = total + item.price;
}
console.log(total);
}
}
Now to my question:
As you can see, I was looping through persons in my html code with *ngFor and in my typescript code in getTotal() again. I only did that to access their items in the following loop (person.items). I wanna get rid of the first loop and access the current element I'm looping through with *ngFor. How can I achieve this or is it even possible?
Just Change It like
As answer to your question , call a function from template side , here
it is but would prefer second method to go
Template Side :
<p>Total <span>{{getTotal(person.items)}}</span></p>
Component Side :
getTotal(items) {
let total = 0 ;
for(let item of items){
total = total + item.price;
}
return total;
}
Better way to do is , process all data from component side , rather than calling it from template side
Why ?
In above case function will be called each time the view changes or data change.
Component Side :
constructor(){
this.persons.map(person => {
person.total = person.items.reduce((pv,cv) => {
return cv.price + pv.price;
});
return person;
});
}
Template Side :
<p>Total <span>{{person.total)}}</span></p>
You can pass person in the getTotal function and can add the price of the items in that without looping again
<div *ngFor="let person of persons">
<p>{{person.name}}</p>
<p>Total <span>{{ getTotal(person) }}</span></p> <!--here I'm calling the function, which will loop through persons again-->
</div>
Typescript
getTotal(person) {
let total = 0;
for(let item of person.items){
total = total + item.price;
}
return total;
}
Send to the getTotal method the person. I mean:
getTotal(person:any){
let total: number = 0;
for(item of person.items){
total += item.price;
}
return total;
}
So in your HTML it must be:
<div *ngFor="let person of persons">
<p>{{person.name}}</p>
<p>Total <span>{{getTotal(person)}}</span></p> <!-- take a look how
I send the current person in the *ngFor loop -->
</div>
I have in a component an array of objects like this:
fields = [
{ abcOptions: [ ... ], abcConfigs: [ ... ] },
{ defOptions: [ ... ], defConfigs: [ ... ] },
{ xyzOptions: [ ... ], xyzConfigs: [ ... ] }
]
In the html, I want to render all these objects to make fields for input. So something like this, and I could just do like this 3 times for the three objects above:
<ng2-selectize [options]="abcOptions" [config]="abcConfigs"></ng2-selectize>
However, to have leaner codes, I want to use ngFor for this task. Moreover, the actual array has like 10 objects, and I don't want to repeat the same code 10 times.
So I would like to attempt something like:
<div *ngFor="let field of fields">
<ng2-selectize [options]="<!--option key here-->" [config]="<!--config key here-->"></ng2-selectize>
</div>
Problem is I'm not sure how to dynamically insert the properties into the code for each iteration, since the keys are different in names. But they have some last letters that are the same, I guess there could be a way to do this. Like [options]="field[*Options]" maybe or something, I don't really know the syntax. Please help.
You could utilize Object.keys() to retrieve the array of values. This solution assumes that options is always at index 0 and config is always at index 1 in any given field object:
HTML
<div *ngFor="let field of fields">
<ng2-selectize [options]="getOptions(field)" [config]="getConfig(field)"></ng2-selectize>
<br />
</div>
TS:
getOptions(field: any): any[] {
return field[Object.keys(field)[0]];
}
getConfig(field: any): any[] {
return field[Object.keys(field)[1]];
}
Here is the example in action.
I would however recommend, if possible, to just consistent property names to avoid needing any kind of methods to extract the values. You could perhaps add an additional property to each field object to specify and utilize the abc/xyz identifies/groupings. With that property you could sort/map/reduce as much as possible needed. That way you could just do something like:
fields = [
{ id: 'abc', options: [ ... ], configs: [ ... ] }
];
<div *ngFor="let field of fields">
<ng2-selectize [options]="field.options" [config]="field.configs"></ng2-selectize>
</div>
Hopefully that helps!
Have this method in your component,
getFromFields(field: any, type: string) {
const value = Object.keys(field).find((key) => (new RegExp(type + '$')).test(key));
if (value) {
return field[value];
}
}
Use it in the template like this,
<ng2-selectize [options]="getFromFields(field, 'Options')" [config]="getFromFields(field, 'Configs')"></ng2-selectize>
I've got the following models associated with sequelize.
Event hasMany Characters through characters_attending_boss
Boss hasMany Characters through characters_attending_boss
Characters hasMany Event through characters_attending_boss
Characters hasMany Boss through characters_attending_boss
These tables are successfully joined and I can retrieve data from them. But when I retrieve the JSON-results the name of the through model gets added to each object, like this:
{
id: 1
title: "title"
-confirmed_for: [ //Alias for Event -> Character
-{
id: 2
character_name: "name"
-confirmed_for_boss: [ // Alias for Boss -> Character
-{
id: 9
name: "name"
-character_attending_event: { // name of through-model
event_id: 1
char_id: 2
}
}
]
-character_attending_boss: { // name of through-model
event_id: 1
char_id: 2
}
}
So I'm looking for a way to hide these "character_attending_boss" segments if possible, preferably without altering the results post-fetch.
Is this possible?
Same issue is solved here: https://github.com/sequelize/sequelize/issues/2541
For me adding through: {attributes: []} to include block works well on Sequelize 2.0
Pass { joinTableAttributes: [] } to the query.
Currently i'm using a custom marshaller to render json:
JSON.registerObjectMarshaller( PlannedEvent) { PlannedEvent pe ->
return [
id : pe.id,
event : [
eventId : pe.baseEvent.id,
subject : pe.baseEvent.subject
],
//rooms: pe.rooms
rooms: [
id : pe.rooms
]
]
}
This gives the following output:
{"id":1,"event":{"eventId":626,"subject":"Baggeren hc (Kv2)"},"rooms":{"id":[8]}}
I would like to know how to set up my map so the value for rooms is a list with each index representing a separate room. Instead of keys, like "id", being set up as a list. The solution in comment gives to much information about the room, so I can't use that.
Wanted result :
"rooms":[{"id":8},{"id":9}]}
If i am correct for your domain modelling you have a hasMany relationship between PlannedEvent & Room .So if you want to get only the list of ROOMS as IDs from the PlannedEvent domian you need to register custom marshallar for Rooms also like :
JSON.registerObjectMarshaller( Room) { Room room ->
// Map of IDs is returned from here
def returnMap = [:]
returnMap["id"] = room.id
return returnMap
}
And in PlannedEvent:
JSON.registerObjectMarshaller( PlannedEvent) { PlannedEvent pe ->
// This is also a map but the value of key rooms will contain the list of IDs of each room
def roomList = [:]
roomList["rooms"] = pe.rooms
return roomList
}
And for next time please clarify your domians & also what do you want clearly.