Array are adding only in 0th index - javascript

I am writing a function in which i need to add the elements into an array.I am getting the data from my database.When add the element into it all the elements are only being added to the Array[0] of the rowData.
private createRowData() {
var rowData:any[] = [];
this.wakanda.catalog.then(ds => {
ds.Group.query({select : 'groupName'}).then(op => {
for(let entity of op['entities']){
rowData.push(
{row : entity.groupName});
}
});
});
return rowData;
}
My output is like this
I need something like this
How do i solve it
Thanks in advance

In the above function you are using DB call which is async and then you are sending the response without waiting for the result.
So, In this case, you will get the rowData.length 0.
send the result after the callback response.
try this:
private createRowData() {
return new Promise((resolve, reject) => {
var rowData: any[] = [];
this.wakanda.catalog.then(ds => {
ds.Group.query({ select: 'groupName' }).then(op => {
for (let entity of op['entities']) {
rowData.push({ row: entity.groupName });
}
resolve(rowData); // Send result from here
});
}).catch(reject);
})
}

Related

How would I be able to return more than one object based on user input amount

Let's say PackInput is an array input.
What I'd like to do's return a dynamic amount of objects depending on how large the input array PackInput is.
For example: if PackInput is [4,5,6], then I'd like three objects returned for each ItemID.
For example: return {... ItemID: 4 ...}, return {... ItemID: 5 ...}, return {... ItemID: 6 ...}.
My current code below is only grabbing the first item of the array instead of all of them and I'm not sure why. I've turned my wheels on this for so long and now I've hit a wall. What am I doing wrong?
for(let i = 0; i < PackInput.length; i++) {
return {
TimestampUTC: Date.now(),
Payload: {
ItemID : PackInput[i]
}
}
}
Updated:
let array = PackInput.map((items) => ({
TimestampUTC: Date.now(),
Payload: {
ItemID : items
}
})
);
let objects = array.reduce(function(target, key, index) {
target[index] = key;
return target;
})
return objects;
You can use the map method to achieve what you want
return PackInput.map((element) => ({
TimestampUTC: Date.now(),
Payload: {
ItemID : element
}
}))
A return statement ends the execution of a function, and returns control to the calling function/upper scope.
Update on object:
const object = PackInput.reduce(function(previousValue, currentValue, index) {
return {
...previousValue,
[index]: currentValue
}
}, {})
You need to provide an empty object as 2nd argument for the reduce function.
You can return an array/object. The problem is that you can call return only once in a function and as soon as a function reaches return it would be returned to the caller scope. You can use the loop to create the array/object and then return the final value:
let array = [];
for(let i = 0; i < PackInput.length; i++) {
array.push({
TimestampUTC: Date.now(),
Payload: {
ItemID : PackInput[i]
}
});
}
return array;

How can I get the value stored in that array 'my_array' Cypress?

cy.get(tableBody)
.each(($el, $index) => {
let myArray = []
let mydata = $el.text()
if($index!==1) {
myArray.push(mydata.trim())
}
}).then((my_list) => {
cy.log(my_list)
Here, my_list print the value same as what cy.get(tableBody) return. It's like cy.get(tableBody).then((my_list) => { cy.log(my_list) }. I want that array and use that later. I know I can get return like this
TableDataBeforeSorting() {
let myArray = []
cy.get(tableBody).each(($el, $index) => {
let mydata = $el.text()
if($index!==1) {
myArray.push(mydata.trim())
}
})
return myArray
But I want it using then so that I can use it later. Any suggestion or feedback will be highly appreciated.
I've found that when Cypress doesn't do what I want in terms of saving data to variables to use later, I can save data to disk:
// save it
cy.XYZcommand().then((results) => {
cy.writeFile('temp.txt', results)
})
...
cy.readFile('temp.txt')
.then((results) => {
// do something with it
})
...
// clean it up
cy.exec('rm temp.txt')

Assigning values received from api calls for each element in the loop iteration using Observables

I have a foreach loop through which I am iterating and want to call functions which would in turn make async api calls and return value which can be rendered in the html.
The 1st function call getCurrentValue() would return currentTemperatureRef which I finally want to assign receivedCurrentValue and render in html
The 2nd function call getDesiredValue1() would return desiredValueToBeReturned which I finally want to assign receivedDesiredValue1 and render in html
ts
myObj = { droppedItem: [] };
elements = [
{ elementId: 1, elementName: "name1" },
{ elementId: 2, elementName: "name2" },
{ elementId: 3, elementName: "name3" },
{ elementId: 4, elementName: "name4" }
];
this.elements.forEach(element => {
let receivedCurrentValue = this.getCurrentValue(element.name);
let receivedDesiredValue1 = this.getDesiredValue1(element.id);
this.myObj.droppedItem.push(receivedCurrentValue)
this.myObj.droppedItem.push(receivedDesiredValue1)
}
getCurrentValue(eleName){
//1st api(async api call)
var ref = this.helperService.getPointIdbyTags(this.existingObj, ['current',
'temp'], eleName)[0];
//2nd api(async api call which expects ref value from above api call)
this.siteService.getHisPointData(ref, 'current')
.pipe(
map(this.helperService.stripHaystackTypeMapping),
)
.subscribe(({ rows }) => {
if (rows.length > 0) {
this.currentTemperatureRef = rows[0].val;
}
});
}
getDesiredValue1(eleId){
//1st async api call
this.siteService.getScheduleParamsByRoomRef('temp and air and desired and
heating', eleId)
.subscribe(function (a) {
let row = a;
let pointId = this.helperService.stripHaystackTypeMapping(row['id']).split(' ')[0];
//2nd async api call expecting pointId from above api call
this.siteService.getHisPointData(pointId, 'current')
.subscribe(function (a) {
let rows = a.rows,
if (rows.length > 0) {
let desiredValueToBeReturned = rows[0].val;
)
}
)
}
}
html
<div *ngFor="let existingItem of myObj?.droppedItem">
<span>{{existingItem.receivedValue}}</span>
<span>{{existingItem.receivedDesiredValue1}}</span>
<span>{{existingItem.receivedDesiredValue2}}</span>
</div>
Update
when I try to
getCurrentValue(eleName){
let roomObj = this.getRoomObj(eleName);
let equipRef = roomObj.map(equip => equip.entities.filter(entity => entity.entities.length > 0)[0])[0];
return this.helperService.getPointIdbyTags(this.buildings, ['current',
'temp'], equipRef.referenceIDs.room)[0].pipe(switchMap((res:any)=>{
//we don't want "res" else the response of
return this.siteService.getHisPointData(res, 'current')
.pipe(
map(this.helperService.stripHaystackTypeMapping),
)
}));
}
I get an error on line => return this.helperService.getPointIdbyTags(this.buildings, ['current',
'temp'], equipRef.referenceIDs.room)[0].pipe(switchMap(
ERROR TypeError: this.helperService.getPointIdbyTags(...)[0].pipe is
not a function
I don't undestand so much the question, but you need understand some about forkJoin and switchMap. SwitchMap it's usefull when you need make two calls one depending the response of the another. The construction becomes like
callOne.pipe(
switchMap(resposeOfCallOne=>{
return callTwo(responseOfCallOne)
})
If subscribe you received the response of callTwo
forkJoin get an array of calls and return the result in an array
forkJoin([callOne,callTwo])
if subscribe you received an array: res[0] has the response of callOne and res[1] the response of callTwo
Well, First convert your functions getCurrentValue and getDesiredValue1 to return observables
getCurrentValue(eleName){
return this.helperService.getPointIdbyTags(this.existingObj, ['current',
'temp'], eleName)[0].pipe(switchMap((res:any)=>{
//we don't want "res" else the response of
return this.siteService.getHisPointData(ref, 'current')
.pipe(
map(this.helperService.stripHaystackTypeMapping),
)
};
}
getDesiredValue1(eleId){
return this.siteService.getScheduleParamsByRoomRef('temp and air and desired and
heating', eleId).pipe(
switchMap((a:any)=>{
let row = a;
let pointId = this.helperService.stripHaystackTypeMapping(row['id']).split(' ')[0];
return this.siteService.getHisPointData(pointId, 'current')
}))
Well, when we has an element we want create the two calls, we are going to use forkjoin
We want to make, forEach element create two calls, so we can make
this.elements.forEach(element => {
forkJoin([this.getCurrentValue(element.name),this.getDesiredValue1(element.id)])
.subscribe(([current,desired])=>{
element.current=current;
element.desired=desired;
})
})
I user in subscribe ([current,desired]) but we can use res and use element.current=res[0],element.desired=res[1]
If we want, we can even make only one subscription -now we has so many subscriptions as element we have-
arrayOfCalls=[]
this.elements.forEach(element => {
arrayOfCalls.push(
forkJoin([this.getCurrentValue(element.name),this.getDesiredValue1(element.id)])
)
}
//then subscribe
arrayOfCalls.subscribe((fullRes:any[])=>{
fullRes.map((res,index)=>{
this.elements[index].currentValue=res[0]
this.elements[index].desiredValue=res[1]
})
})

I'm looking for a way to remove items from my select array based on values of other array

I'm trying to remove from select array the options who match with my other array, both come from api and are beeing displayed through ngFor, i'm already trying to do it using filter but with no success, code below as follow:
loadUnidadeUsuarios() {
return this.restApi.getUnidadeUsuarios(this.id).subscribe((data: UnidadeUsuario) => {
this.unidadeUsuarioData = data;
});
}
Then after load UnidadeUsuarioData i need to remove the users who match:
loadUsuarios() {
return this.restApi.getUsuarios().subscribe((data: Usuario) => {
this.Usuario = data;
this.Usuario = this.Usuario.filter(usuario => usuario.id !== this.unidadeUsuarioData.id )
});
}
But with no success
the filter it's looks like
this.Usuario.filter(usuario=>!this.unidadeUsuario.find(x=>x.id==usuario.id)
But you must take account if you need wait to the two calls finish. For this use switchMap
this.restApi.getUnidadeUsuarios(this.id).pipe(
switchMap((res: any[]) => {
//..here you has your getUnidadeUsuario...
//but you want the others usuarios
return this.restApi.getUsuarios().pipe(map((usuarios: any[]) => {
//in usuarios you has all the usuarios
//but you want filtered
return usuarios.filter(u => !res.find(x => x.id == u.id))
}))
})
).subscribe(usuarios => {
console.log(usuarios)
})
To achieve expected result, with just two loops, use below option
Convert unidadeUsuarioData as obj with id values
Filter Usuario to check whether unidadeUsuarioData has property id
loadUsuarios() {
let unidadeUsuarioDataObj = this.unidadeUsuarioData.reduce((acc, v) => {
acc[v.id] = v;
return acc
}, {})
this.Usuario = this.Usuario.filter(usuario => !unidadeUsuarioDataObj[usuario.id])
console.log(this.Usuario)
}
stackblitz for reference- https://stackblitz.com/edit/angular-dapycb?file=src/app/app.component.html

Promise.resolve() return only one element in nested array

Here is my code:
search(): Promise<MyModel[]> {
const query = {
'action': 'update',
};
return new Promise((resolve, reject) => {
this.api.apiGet(`${API.SEARCH_STUDENT}`, query).then((data) => {
const a = data.items.map(i => i);
const b = data.items.map(i => i);
console.log(a.array1[0].array2.length); // 1
console.log(b.array1[0].array2.length); // 5
resolve(a);
}, (error) => {
reject(error);
});
});
}
MyModel class:
class MyModel {
...
array1: [{
array2: []
}]
}
data.items[0].array1[0].array2 returned by function apiGet contains 5 elements. But if I put a or b into resolve function, it now just keep first element only like the comments in the snippet.
Could anyone show what I miss here?
Firstly I am not sure why you wrap a promise in a promise.. why do you need to do that when
this.api.apiGet returns a promise.
Also, why are you trying to map? I bet if you console.log(data.items) the same data would come back. I think you have just got a little confused with your code. A tidy up of the code should resolve all of this for you.
I would do something like the below, now every time you call search you get all the data back which you can use when you want it.
search(): Promise<MyModel[]> {
const query = {
'action': 'update',
};
return this.api.apiGet(API.SEARCH_STUDENT, query)
.then((data) => data as MyModel[]));
}

Categories

Resources