array to ObjectList angular - javascript

import { Board } from './board';
export class Notification {
id : number ;
startDate : Date = null;
endDate : Date = null;
message : string = '';
notificationBoards: Board[] ;
}
Board class
export class Board {
id : number = 0;
name : string = '';
createDate : Date = null;
createdBy : number ;
}
Coponent class is
message.component.ts
///..
submitForm(obj) {
console.log("obj - "+obj);
let notificationObj:Notification = new Notification();
let selectedBoard: Board[];
notificationObj.startDate = obj.startDate;
notificationObj.endDate = obj.endDate;
notificationObj.message = obj.message;
notificationObj.notificationBoards = obj.board;
console.log("notificationObj.notificationBoards"+notificationObj.notificationBoards.length);
for (let i = 0; i < notificationObj.notificationBoards.length; i++) {
console.log(":::"+notificationObj.notificationBoards[i] +":::");
}
...///
I am able to add the notification but unable to add the board obj inside notification object. Board is a list of boards.
obj.board - is an array {10,20,...} which is boardId.
I want to add this array to Board[] and send to service layer.
let selectedBoard: Board[]; is the board list and I want to push notificationObj.notificationBoards[i] to selectedBoard[i] and so on.
Basicaly want to add array to object list Board[].Can someone please help.

Your obj.board is a plain array of numbers (boardIds as you explained), notificationObj.notificationBoards is an array of Board objects.
Typescript would not allow you to convert an object array of type Board class into an array of number values..
You'll have to map one array type to another something like this.
notificationObj.notificationBoards = obj.board.map(boardId=>{
let boardObj:Board = new Board();
boardObj.id = boardId; //since we have only one element (boardId), other fields of board object are not set.
return boardObj;
});
Thanks.

Related

Function to format and add object to array not functioning properly

My component has a state array "bets" consisting of bet objects. The function in question creates an empty "records" array to house formatted records to be stored in the database.
const placeBets = () => {
//determine type of bet(s) - single,parlay,etc.
if(slipType === "single"){
let records = [];
bets.forEach(bet=>{
let tmpModel = formatSingleBet(bet)
records.push(tmpModel);
})
console.log(records);
}
}
I run a for each loop on the bets array to format each bet calling the formatSingleBet function.
//Function to format single bets in records for db storage
const formatSingleBet = (bet) =>{
//create instance of bet model obj and add properties
let betModel = model;
betModel.type = slipType;
betModel.wager = bet.wager;
betModel.odds = bet.odds.decimal;
betModel.result = "";
let legType = bet.type;
if(legType === "Spread"){
//create instance of spread line object
let spread = Spread;
spread.team.type = bet.team.type;
spread.team.name = bet.team.name;
spread.line = bet.handicap;
spread.result = "";
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = spread;
betModel.legs[0].odds = bet.odds.decimal;
}else if(legType === "3-Way Moneyline"){
//create instance of ML line object
let ml = ML;
ml.team.type = bet.team.type;
ml.team.name = bet.team.name;
ml.result = "";
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = ml;
betModel.legs[0].odds = bet.odds.decimal;
}else if(legType === "Total"){
//create instance of Total line object
let total = Total;
total.result = "";
total.bet = bet.bet;
total.line = bet.total;
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = total;
betModel.legs[0].odds = bet.odds.decimal;
}
return {
contestPlayerID: match.params.entryid,
jsonBet: betModel
};
}
I create an instance of the model object, and set the properties depending on the "leg type" of the bet. I then return the formatted bet to be inserted into the records array which is then returned.
The issue is that regardless of the differences in the bet, the betModel object is always returned as the last bet in the bets array.
One thing I noticed is that when I log the betModel it appears to be different for each bet, however the property values change when drilling into the object.
Please help, any advice would be wonderful.
By assigning betModel = model you are simply creating a reference to model and all the changes you make to betModel will also be made to model. This means that model is not a blank prototype, but contains the values of the last bet that you processed.
In order to use model as a prototype in the way you seem to intend use spread syntax to assign a copy to betModel.
let betModel = {...model}
const spreadSource = { a: 1, b: 2 };
const spread = {...spreadSource};
spread.c = 'Added'
console.log('spread: ', spread);
console.log('spreadSource: ', spreadSource);
const referenceSource = { a: 1, b: 2 };
const reference = referenceSource;
reference.c = 'Added';
console.log('reference: ', reference)
console.log('referenceSource: ', referenceSource)

getting the value of static method in javascript class

i can't figure it out on how to get the values of a static method of a class. my code is below.
class Field {
constructor(rows = 11, cols = 10) {
this.numRows = rows
this.numCols = cols
}
static loadFromFileContents(contents) {
this.numCols = contents.split('x')[0]
this.numRows = contents.split('x')[1]
}
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)
first of all, i want to get the instance of the static method. something like this instanceof(field), it should be equal to 'Field'. but i don't know if my syntax is correct for getting the instance. Second i want the return value of field.numCols should be equal to 4 because of the first split value and
field.numRows should be equal to 5. sorry i'm not that familiar with static method of a class. i hope you can help me with my problem. thank you so much.
It sounds like the static method needs to parse the passed string and return a new Field instance:
class Field {
constructor(rows = 11, cols = 10) {
this.numRows = rows
this.numCols = cols
}
static loadFromFileContents(contents) {
const [rows, cols] = contents.split(' x ');
return new Field(rows, cols);
}
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)

compare the current and previous version of the same array for change in value in javascript

I have a following data array :
[{"name":"joseph","time":"0","status":"Idle"}] //there are multiple objects inside the array
This array of objects is generated every second by a node js service. I want to compare the newly created array with the previously created array to check for the change of the status.
eg
case 1
newly created
[{"name":"joseph","time":"0","status":"Idle"}]
previously created
[{"name":"joseph","time":"0","status":"Idle"}]
comparing the status of new and previous object : No change in status
case 2
newly created
[{"name":"joseph","time":"0","status":"Calling"}]
previously created
[{"name":"joseph","time":"0","status":"Idle"}]
comparing the status of new and previous object : status has changed
I hope you get the point.
If the status has changed then assign the current time to the time key;
I'm not able to figure out how to save the previous array and compare it with the newly created array.
What I have done so far:
newarray = [{"name":"joseph","time":"0","status":"Calling"}];
previousarray = newarray;
for(i=0;i<=newarray.length;i++){
for(j=0;j<previousarray.length;j++){
if(previousarray[j].status != newarray[i].status){
newarray[i].time = moment().format('H:mm:ss');
}
}
}
but this doesn't work. I get error like :
TypeError: Cannot read property 'status' of undefined
How do I do it?
First your previousArray is a reference to the newArray using =
Use the spread operator syntax instead:
const previousArray = [...newArray];
Then in the first loop you have <= instead of <
const newarray = [{"name":"joseph","time":"0","status":"Calling"}];
const previousarray = [...newarray];
for(let i = 0; i < newarray.length; i++) {
for(let j = 0; j < previousarray.length; j++) {
if(previousarray[j].status != newarray[i].status) {
newarray[i].time = moment().format('H:mm:ss');
}
}
}
can do in the below possible way. assuming newly_created & previously_created
newly_created = [{"name":"joseph","time":"0","status":"Calling"}, {"name":"joseph - 2","time":"0","status":"Idle"}, {"name":"joseph - 3","time":"0","status":"Calling"}];
previously_created = [{"name":"joseph","time":"0","status":"Idle"}, {"name":"joseph - 2","time":"0","status":"Calling"}, {"name":"joseph - 3","time":"0","status":"Calling"}];
newly_created.forEach(function(newArrObj, index){
if(newArrObj.status !== previously_created[index].status){
// newArrObj.time = moment().format('H:mm:ss');
newArrObj.time = new Date().toTimeString().split(' ')[0];
}
});
console.log('New Array : ', newly_created);
I think you want to do something like this:
newarray = {"name":"joseph","time":"0","status":"Calling"};
previousarray = newarray;
if(previousarray['status'] !== newarray['status']){
newarray['time'] = "date-time";
}

iterate through Json array and get nested object's value Typescript

I have an array with to access a list of properties which i have manage to get the value of these properties however, there is a nested object "Region" in the list which has a specific property "regionName" that i would like to retrieve the value, please check the code and uploaded images for reference.
I hope to this made sense. Thank You in advance
export function CreateStores(xhttp: XMLHttpRequest, storeArray?: Array<PromotionClasses.Store>) {
while (STORE_TABLE.rows.length > 1) {
STORE_TABLE.deleteRow(1);
}
if (storeArray == undefined) {
//Convert the response into an array of objects
storeArray = JSON.parse(xhttp.responseText) as Array<any>;
}
CheckForDuplicateStores(storeArray);
//Get the current row length of the table so we know where to append to
let tableRowLength = STORE_TABLE.rows.length as number;
console.log("Store array is");
// console.log(storesInPromotionArray);
for (let i = 0; i < storeArray.length; i++) {
//A dictionary containing the key value pair of the stores properties
let tableData = {};
//Add the store's id to the storeArray
let store = new PromotionClasses.Store(storeArray[i]["StoreName"], storeArray[i]["id"]);
storesInPromotionArray.push(store);
console.log(storeArray[i]["region"]);
var check = storeArray[i]["region"];
//let attr = new PromotionClasses.Attribute(storeArray[i].name, storeArray[i].type, storeArray[i].property);
//Assingattributes.push(attr);
//Create and insert a new row
let row = STORE_TABLE.insertRow(tableRowLength);
//row.contentEditable = 'true'
//The first three cells will always be the row number, store number and name
tableData["#"] = i.toString();
tableData["Number"] = storeArray[i]["storeNumber"];
tableData["Name"] = storeArray[i]["storeName"];
tableData["addressLine"] = storeArray[i]["addressLine"];
tableData["postcode"] = storeArray[i]["postcode"];
//****NESTED OBJECT PROPERTY = regionName
tableData["region"] = storeArray[i]["region"];

Sort document collection by values total in xpages

I'm working on an xpages application in which I would like to display the top5 of the total volumes per client.
I have a list of customers who buy any number of products.I would like to classify customers according to the total volume of products purchased.
I use the "Top5" View categorized by customer.
I used a document collection to calculate the total volume by customer.
I get to classify volumes in descending order and select the top 5.But this does not allow me to retrieve the name of the product and the client from the view.
var cls3 = #DbColumn("","Top5",1);
sessionScope.put("clientsList3",cls3);
var db=session.getCurrentDatabase();
var view7=db.getView("Top5")
var dataa =[] ;
var top =[];
for(var r = 0; r < clientsList3.length; r++){
var Cli = #Trim(#Text(clientsList3[r]));
var VolumeTotal :NotesDocumentCollection = view7.getAllDocumentsByKey(Cli);
var vola = 0;
var array = new Array();
var prod = "";
if (VolumeTotal == 0) {array = 0;}
else{
var doca = VolumeTotal.getFirstDocument();
while (doca != null)
{vola = vola + doca.getItemValueInteger("TotalVolume_Intermediate");
doca = VolumeTotal.getNextDocument(doca);
}
array.push(vola);
}
dataa[r] = array;
dataa.sort(function(a, b) {return b - a;});
top = dataa.slice(0,5);
}
return dataa;
}
You do want to use a managed bean for that, it makes a lot of things much easier. You create a custom class that does the compare operation for you:
public Class TopSeller implements Comparable {
String product;
public String getProduct() {
return this.product;
}
public void setProduct(String product) {
this.product = product;
}
// Add properties as needed
public int compareTo(Topseller theOther) {
// Your ranking code goes here
}
}
In that class your compareTo function does provide the ranking and ordering. Then you just need:
Set<TopSeller> allSeller = new TreeSet<TopSeller>();
... and you are done. The Treeset will provide the ready sorted result and you just bind it to a repeat with 5 rows to display

Categories

Resources