Map json Array in static method (Angular2+TS) - arrays

Problem to get the syntax right to map my incoming data in a static method. My json Array looks like this:
[
{
"documents": [
{
"title": "+1 (film)",
"is-saved": false,
"abstract": "some text",
"id": "_1__film_",
"url": "some url"
}
]
}
]
Each item in that array is a Result.
As an example to refer to Mapping one Result I know how to do:
static resultFromJSON(json): Result {
let documents: SearchQueryDocument[] =
json.documents.map(doc => new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url))
return new Result(documents)
}
But I need to map the whole array, so how do I do that?
static resultsFromJSON(json): Result[] {
let results: Result =
json.map ... // what here?
}
Mapping one result I can use json.documents.map... but mapping the whole array it has no "name" to use...
Maybe a stupid question from a newbie, but any help is appreciated!

If I understand you correctly then your json corresponds to the following interfaces:
interface IDocument {
title: string;
"is-saved": boolean;
"abstract": string;
id: string;
url: string;
}
interface IResult {
documents: Document[];
}
And then you have an array of Result.
To map that json you can do:
static resultsFromJSON(json): Result[] {
return json.map(obj => {
new Result(obj.documents.map(doc => {
return new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url);
}));
});
}

The solution that worked for me was just a slight change to the above static method by Nitzan Tomer.
This worked:
static resultsFromJSON(json): Result[] {
return json.map(obj =>
new Result(obj.documents.map(doc =>
new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url)
))
)
}

Related

Error: Response is not a function, when trying to find if the name exists

So I'm using mongodb to fetch some data from the database.
The issue is when I try to check for something in an array
Here is what the structure looks like:
Example array structure
{ // ...
likedPeople: [
{
name: "foo"
image: "test",
},
{
name: "bar",
image: "baz",
}
]
}
This is the array i get Back.
So when i try to find if it includes a certain value,
eg:
const displayName = "foo";
console.log(
likedPeople.map((likedPerson) => {
return likedPerson.name === displayName; // Output: [true, false]
})
);
But then If i again try to do some other method on it like map() or includes(), It breaks the setup:
const response = likedPerson.name === displayName; // Output: [true, false]
response.map((res) => console.log(res)); // Output: ERROR: response.map() is not a function
But the fact is that I am getting an array with the values, so what am I even doing wrong here?
I tried adding an optional chaining response?.map() but still it gave me the same error.
Also the includes() method also returns me the same response.includes is not a function error.
Can anyone help?
Use the some method to check the name exists in likedPeople :
const likedPeople = [
{
name: "foo",
image: "test",
},
{
name: "bar",
image: "baz",
}
];
const displayName = "foo";
const isExist = likedPeople.some(people => people.name === displayName);
console.log(isExist)

How can I realize "find" with using "$in" by two parameters in mangoose?

Hi I have the function which get object with id array like this.
{
"participants": [
"5fa566b5b96a9407c804ccd4",
"5fa5639cb96a9407c804ccce"
]
}
And I need to find object which have exactly this fields
Objects in which i try to find it looks like this:
{
"_id" : ObjectId("5fac288e53a6a72e94f721fa"),
"participants" : [
ObjectId("5fa566b5b96a9407c804ccd5"),
ObjectId("5fa5639cb96a9407c804ccc5")
],
"messages" : [],
}
I am trying to do like this but it doesn't work.
async filterDialog(newDialog: any){
const res = await Dialog.find({
'participants': { $in: { ...newDialog.participants } }, function(err: any, dialog: any) {
if (err) {
return err
} else {
return dialog
}
},
})
return res;
}
Will be glad if someone help me.
I think you need $all operator.
Check this query:
db.collection.find({
"participants": {
"$all": yourArray
}
})
Only return the document where the field participants contains all element from the given array.
Example here where I've used numbers instead of ObjectId to read easier.
Please check if this is the behavior you expect.

Reading JSON into arrays in Angular (HttpClient)

i am trying to read JSON into different arrays using HttpClient for the use in Echarts, but since i am a newbie i couldn't find how to fill JSON into the different arrays.
the part code i used so far was:
....
label: Array<any>;
data: Array<any>;
tooltip: Array<any>;
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
this.data=data.data;
this.label=data.label;
this.tooltip=data.tooltip;
console.log(data)
});
}
public getJSON(): Observable<any> {
return this.http.get("./assets/JSONData/TeamProgress.json")
}
the JSON file is formatted like this:
[{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
...etc
i want to be able to get all labels of JSON in one array, and all data in another array, and all tooltips in a third array.
it would be great if you can help me.
thanks
First the result of that file should be a valid JSON structure aka (an object with key-values) you can group the array under a key called per example result
{
"result": [
{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
//....Etc
]
}
Then you can access the data and filter it using map as below:
this.getJSON().subscribe((data:any) => {
this.label = data.result.map(element =>
// if you want to return an array of objects
{return {"label": element.label}}
// or if you want to return the raw values in an array, just do
element.label
});
this.data = data.result.map(element => {
return {"data": element.data}
});
this.tooltip = data.result.map(element => {
return {"tooltip": element.tooltip}
})
})

How to extract array from json on Angular

I'm working with angular2 ( version 5).
I make an http request an get back json.
I know how to access and use value but not the array.
and I don't find how to extract the two array inside element.
here my json:
{ "ImpiantiProva": [
{
"nomeImpianto":"MFL1",
"descrImpianto":"Multifilo 1",
"posizione":"Place1",
"dati_status": "true",
"unita_misura": "m/s",
"vel_attuale": 11.5,
"vel": [24.5,13.6,34.6,12.1],
"orario": ["17.05","17.06","17.07","17.08"]
},
{
"nomeImpianto":"MFL2",
"descrImpianto":"Multifilo 2",
"posizione":"Place2",
"dati_status": "true",
"unita_misura": "m/s",
"vel_attuale": 12.5,
"vel": [24.5,13.6,34.6,12.1],
"orario": ["17.05","17.06","17.07","17.08"]
}
]
}
In the data.service.ts I have the http request and it store values on :
stream$: Observable<ImpiantoModel[]>;
here my definition of the model:
#impianto.model
export class ImpiantoModel {
nomeImpianto: string;
descrImpianto: string;
posizione: string;
dati_status: string;
unita_misura: string;
vel_attuale: number;
vel: VelocitaModel[];
orario: OrariModel[];
}
#orari.model.ts
export class OrariModel {
orario: string;
}
#velocita.model.ts
export class VelocitaModel{
vel : number;
}
is it the right why to define my object?
How can I use the array "vel" and "orario"?
How can I print (access) the array "vel" of machine with "nomeImpianto" = "MFL1" ?
and how can I copy the array "vel" on new array?
thank you very much!
Here is what I understood of what you want to do : get the item in your json resp and put it in your object , so the best way is to create a static method directly when you get the json response, before returning the value create this adapter adaptImpiant(jsonObj) which will do something like :
adaptImpiant(jsonObj) {
let impiantTab = [];
jsonObj.ImpiantiProva.forEach((item) => {
let impiantoModel = {};
// impiantoModel = item if the model (below) match the item;
// if not manually set all your var like your velocita
let velocita = [] // is an array or an object with an array
// if class velocita = {}
velocita = item.vel.slice(0);
// if class velocita.valuesTab = item.vel.slice(0);
impiantoModel.velocita = velocita;
impiantTab.push(impiantoModel);
}
}
Your model seems wrong in this case, because you already use a ImpiantoModel array, so just create a class with whatever you want in :
#impianto.model
export class ImpiantoModel {
nomeImpianto: string;
descrImpianto: string;
posizione: string;
dati_status: string;
unita_misura: string;
vel_attuale: number;
vel: VelocitaModel // or simply [];
orario: OrariModel // or simply [];
}
I'm not sure I understand you, but I'll try.
is it the right why to define my object?
It should be:
export class ImpiantoModel {
nomeImpianto: string;
descrImpianto: string;
posizione: string;
dati_status: string;
unita_misura: string;
vel_attuale: number;
vel: Array<string>;
orario: Array<string>;
}
(But I have to confess, I don't know why model and not an interface)
How can I use the array "vel" and "orario"?
What do you mean?
How can I print (access) the array "vel" of machine with
"nomeImpianto" = "MFL1"
const thisContainsTheDataFromVel = whereYourDataIsStored['ImpiantiProva'].find((item) => { item['nomeImpianto'] === 'MFL1'})['vel'];
and how can I copy the array "vel" on new array?
UPDATE after reading your comment under this answer:
I took code from your example and added what you are missing. I made it so it can be more reusable (it can be enhanced even more, but I hope you understand the code and do what you need).
copyArray(data, targetValue) {
const mfl1Data = data.find((item) => item['nomeImpianto'] === targetValue);
if (mfl1Data) {
return mfl1Data.vel;
}
return [];
}
getdata2() {
this.http.get<ImpiantoModel[]>(this.myUrl)
.subscribe(
data => {
this.variableToStoreIn = this.copyArray(data, 'MFL1');
data.forEach(item => {
this.sub$.next(item);
});
});
return this.sub$;
}
CopyArray finds the data and returns it. If you don't want it like this, but just set a value of some property to the value of vel array then you can change it to:
copyArray(data) {
const mfl1Data = data.find((item) => item['nomeImpianto'] === targetValue);
if (mfl1Data) {
this.yourVariable = mfl1Data.vel;
}
}
If this answer is sufficient, please consider to mark it as the best answer, thank you.
According to your model classes, your JSON is wrong. You should have something like this:
{ "ImpiantiProva": [
{
"nomeImpianto":"MFL1",
"descrImpianto":"Multifilo 1",
"posizione":"Place1",
"dati_status": "true",
"unita_misura": "m/s",
"vel_attuale": 11.5,
"vel": [
{
"vel": 24.5
},
{
"vel": 13.6
}
...
],
"orario": [
{
"orario": "17.05"
},
{
"orario": "17.06"
}
...
]
}
]
}
Your model expects ImpiantoModel.vel and ImpiantoModel.orario to be arrays of objects. In your JSON response one is an array of numbers and the other of strings.
An if you want to use it in an HTML template, considering that you have a class attribute in your .ts file like this:
private impiantoModels: ImpiantoModel[];
You could do something like this inside your .html template:
<div *ngFor="let impModel of impiantoModels">
...
<div *ngFor="let v of impModel.vel">
<p>{{v.vel}}</p>
</div>
<div *ngFor="let o of impModel.orario">
<p>{{o.orario}}</p>
</div>
</div>

Angular2 Mapping nested json array to model

I am not able to map the nested json array which is response from Web to my model array in Angular2. Suppose I have json array response as below:
[{
"base_url": "http://mysearch.net:8080/",
"date": "2016-11-09",
"lname": "MY PROJ",
"name": "HELLO",
"description": "The Test Project",
"id": 10886789,
"creationDate": null,
"version": "2.9",
"metrics": [{
"val": 11926.0,
"frmt_val": "11,926",
"key": "lines"
},
{
"val": 7893.0,
"frmt_val": "7,893",
"key": "ncloc"
}],
"key": "FFDFGDGDG"
}]
I was trying to manually map the fields referring the link Angular 2 observable doesn't 'map' to model to my model and was able to display those in my HTML by iterating through ngFor.....but I want to also display ncloc and lines value also in the HTML but I am not sure how to map those values to my Model array like mentioned in the above link.
Can you please help me with this?
Thanks.
EDIT
Mode class
export class DeiInstance {
base_url: string;
date: string;
lname : string;
name : string;
id : number;
key:string;
constructor(obj: DeiInstance) {
this.sonar_url = obj['base_url'];
this.lname = obj['lname'];
this.name = obj['name'];
this.id = obj['id'];
this.key = obj['key'];
this.date = obj['date'];
}
// New static method.
static fromJSONArray(array: Array<DeiInstance>): DeiInstance[] {
return array.map(obj => new DeiInstance(obj));
}
}
You can simplify your model and your mapping a lot.
You don't need to map your API response manually. JavaScript/TypeScript can do this for you.
First you need multiple interfaces.
export interface DeiInstance {
base_url: string;
date: string;
lname: string;
name: string;
description: string;
id: number;
creationDate: string; //probably date
version: string
metrics: Metric[];
key: string;
}
export interface Metric {
val: decimal;
frmt_val: decimal;
key: string;
}
You can then use the as-"operator" of TypeScript to cast your API response to the DeiInstance Type.
sealSearch(term: string): Observable<DeiInstance[]> {
return this.http.get(this.sealUrl + term)
.map(response => response.json() as DeiInstance[])
.catch(this.handleError);
}
If you use interfaces instead of classes you have also the advantage that you have less production code which will be sended to the client browser.
The interface is only there for pre-compile-time or however you want to call it.
Hope my code works and it solves your problem.

Resources