How can I group(map) by data for ID? - arrays

How can I group my data by CustomerID?
It's does not work, I am trying different way but I think I don't understand this structure
This is my code:
function CustomerGroup() {
this.$http.post(auth.API_URL + 'api/ProblemsSupports/ProblemsList', null, {
headers: {
'Authorization': 'Bearer ' + auth.getAuthHeader()
}
}).then((response) => {
this.problemitems = response.body
const map = this.problemitems.map(e => (map[e.CustomerID] = map[e.CustomerID]))
return map
this.progress = false
}, (response) => {
if (response.status === 0) {
this.text1 = ' !!!'
this.snackbar = true
this.progress = false
} else {
this.text1 = '!!!!!!'
this.snackbar = true
this.progress = false
}
})
}

For example you can use this function:
groupBy (list, keyValue) {
const map = new Map()
list.forEach((item) => {
const key = item[keyValue]
const collection = map.get(key)
if (!collection) {
map.set(key, [item])
} else {
collection.push(item)
}
})
return Array.from(map.values())
}
then just call it
const map = groupBy(this.problemitems, 'CustomerID')
You can use function in Vue methods, then don't forget this

Related

Why my const var is empty but the related filter works

RemoveArea(area: models.Area) {
let messages: string[] = [];
messages = messages.concat(this.getMessagesFromDeletingArea(area));
this._translate.get('QuestionGroup_RemoveAreaConfirm',
{ thisCaption: area.caption[this.BlueContext.currentLanguage] }).subscribe(nextCaption => {
this.dialogsService.confirm(nextCaption, messages)
.subscribe(confirmed => {
if (confirmed) {
this._areaService.removeArea(this.dashboardConfiguration, area, this.BlueContext.currentLanguage);
const index = this.areas.findIndex(a => a.id === area.id);
if (index > -1) {
this.areas.splice(index, 1);
//here
this.dashboardConfiguration.widgets.forEach(wAId => {
const allWidgetByAreaId = wAId.widgets.filter(w => w.areaId === area.id);
allWidgetByAreaId.forEach(w => {
w.areaId = null;
});
});
}
}
});
});
}
The filter is working but the const var (allWidgetByAreaId) is undefined and empty so "for each " does not work. Would you please help?

react-beautiful-dnd: Prevent flicker when drag and drop a lists with API call

I'm using this react-beautiful-dnd library to be able to reorder lists. However, even though I'm able to drag and drop and re-order, there is a flicker when I try to move a card from one list to another list I call API when a card is dragged to the destination list
const onDragEnd = (result: any) => {
if (!result.destination) {
return;
}
const listCopy: any = { ...elements };
const sourceList = listCopy[result.source.droppableId];
const [removedElement, newSourceList] = removeFromList(
sourceList,
result.source.index
);
listCopy[result.source.droppableId] = newSourceList;
const destinationList = listCopy[result.destination.droppableId];
listCopy[result.destination.droppableId] = addToList(
result.destination.droppableId,
destinationList || [],
result.destination.index,
removedElement,
result.source.droppableId
);
setElements(listCopy)};
and in addToList function I am calling API to update order on server
const addToList = (
changedList: string,
list: any[],
index: number,
element: any,
currentListId: string
) => {
let cardOrder;
const result = Array.from(list);
result.splice(index, 0, element);
const cardCurrentIndex = result.findIndex((item) => item.id === element.id);
if (list.length === 0) {
cardOrder = DEFAULT_PIPELINE_ORDER;
} else if (cardCurrentIndex === 0 && result.length !== 0) {
const nextCardOrder = result[1];
cardOrder = nextCardOrder.current_stage_order - STAGE_INCREMENT_AMOUNT;
} else if (cardCurrentIndex === result.length - 1) {
const nextCardOrder = result[result.length - 2];
cardOrder = nextCardOrder.current_stage_order + STAGE_INCREMENT_AMOUNT;
} else if (
Boolean(result[cardCurrentIndex - 1]) &&
Boolean(result[cardCurrentIndex + 1])
) {
cardOrder = Math.round(
(result[cardCurrentIndex - 1].current_stage_order +
result[cardCurrentIndex + 1].current_stage_order) /
2
);
}
let candidatesData: any = elements;
if (candidatesData) {
if (currentListId === changedList) {
candidatesData[changedList as any] = result as unknown as elementsType;
setElements([...candidatesData]);
} else {
candidatesData[currentListId as any] = candidatesData[
currentListId as any
]?.filter((item: any) => item.id !== element.id);
candidatesData[changedList as any] = result as unknown as elementsType;
setElements([...candidatesData]);
console.log("[...candidatesData]", [...candidatesData]);
}
}
const stageId = stagePipeLineLanes?.find(
(item) => item.id.toString() === changedList.toLowerCase()
)?.id;
if (
changedList === "applied" ||
changedList === "sourcing" ||
changedList === "interviewing"
) {
const changedDestination = changedList;
const destinationStages = positionDetails?.candidate_stages.filter(
(item) =>
item.pipeline.toLowerCase() === changedDestination.toLowerCase()
);
const stage = destinationStages.find((item) => item.is_default === true);
mutate(
{
candidateId: element.id.toString(),
data: compressObject({
stage: stage?.id.toString(),
}),
},
{
onSuccess: (response) => {
if (response) {
toast.success(
`Candidate moved to ${capitalizeFirstLetter(
changedDestination
)}`
);
}
},
}
);
} else {
mutate({
candidateId: element.id.toString(),
data: compressObject({
stage: stageId?.toString() || "",
current_stage_order: cardOrder?.toString() || "",
}),
});
}
return result;
};

How to wait for .map() to finish and generate new keys in the array[index]

I'm trying to generate an array with values as follows:
{ name: 'John', age: 35, employer: 'ABC', paycheck: 5,000, last_paycheck: 4,900, change: 100 } // new array
with the initial values in the array as follow:
{ name: 'John', age: 35, employer: 'ABC' } //inital array
the function convertData() is handling all the array conversion.
async function convertData(data){
if(data.length === 0) return data;
// generates new array
const convertedDataArray = await data.map( async (row) =>{
let name = row.name
let paycheck = 0;
let last_paycheck = 0;
let change = 0;
const response = await axios.get('/getData', {params: {
name,
}});
let apiData = response.data.data;
if(apiData.length > 0){
let newData = apiData[0];
let oldData = apiData[1];
change = newData.payCheck - oldData.payCheck;
paycheck = newData.payCheck;
last_paycheck = oldData.payCheck;
}
console.log(apiData); // prints records up to 100 elements
return {...row, paycheck, last_paycheck, change };
});
console.log(convertedDataArray);// prints [Promise]
return Promise.all(convertedDataArray).then(() =>{
console.log(convertedDataArray); // prints [Promise]
return convertedDataArray;
});
};
where convertData() is called:
const response = await axios.get('/getEmployees',{params: {
token: id,
}});
const dataRows = response.data; //inital array
const tableRows = await convertData(dataRows);
return Promise.all(tableRows).then(() =>{
console.log(tableRows); // prints [Promise]
dispatch(setTableRows(tableRows));
});
I'm not sure why i keep getting Promise return I am still learning how to use promise correctly. Any help would be great, thank you in advance!
You should get a array of promises and use Promises.all to get all the data first.
Then use map() function to construct your data structure.
Example below:
async function convertData(data) {
try {
if (data.length === 0) return data;
const arrayOfPromises = data.map(row =>
axios.get("/getData", {
params: {
name: row.name,
},
})
);
const arrayOfData = await Promise.all(arrayOfPromises);
const convertedDataArray = arrayOfData.map((response, i) => {
const apiData = response.data.data;
let paycheck = 0;
let last_paycheck = 0;
let change = 0;
if (apiData.length > 0) {
const newData = apiData[0];
const oldData = apiData[1];
change = newData.payCheck - oldData.payCheck;
paycheck = newData.payCheck;
last_paycheck = oldData.payCheck;
}
return { ...data[i], paycheck, last_paycheck, change };
});
return convertedDataArray;
} catch (err) {
throw new Error(err);
}
}
(async function run() {
try {
const response = await axios.get("/getEmployees", {
params: {
token: id,
},
});
const dataRows = response.data;
const tableRows = await convertData(dataRows);
dispatch(setTableRows(tableRows));
} catch (err) {
console.log(err);
}
})();

How wait a "Array for each" function?

I got a little problem with synchronous/asynchronous system in the function "Array.foreach".
I don't know how to force my code to wait its end.
I tried to use await/async system but my code did not wait the code in "async responseDB =>".
This is my class:
...
let responsesDTO = [];
await Array.prototype.forEach.call(await searchResponsesByQuestionAndUserId(questions[cpt].idquestion, idUser), async responseDB => {
if(responseDB !== undefined){
const responseDTO = {
response_id:0,
response_text:"",
response_type:""
}
const responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text= responseEntity.text;
responseDTO.response_type= responseDB.type;
responsesDTO.push(responseDTO);
}
});
questionResponse.responses=responsesDTO;
questionResponses[cpt]=questionResponse;
}
Could you help me please? Thanks in advance.
I had to mock your async functions. However, the relevant part is to use for..of instead of forEach
async function searchResponsesByQuestionAndUserId() {
let responsesDB = [];
for (let i = 0; i < 10; i++) {
responsesDB.push({
response_id: parseInt(1000 * Math.random(), 10),
type: 'whatever ' + i
});
}
return new Promise((res) => {
window.setTimeout(() => {
res(responsesDB);
}, 1500);
});
}
async function searchResponseByResponseId(response_id) {
return new Promise((res) => {
window.setTimeout(() => {
res({
text: 'text for response ' + response_id
});
}, 300);
});
}
async function getResponsesDTO() {
let responsesDTO = [],
responsesDB = await searchResponsesByQuestionAndUserId();
for (let responseDB of responsesDB) {
if (responseDB === undefined) {
continue;
}
let responseDTO = {
response_id: 0,
response_text: "",
response_type: ""
},
responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text = responseEntity.text;
responseDTO.response_type = responseDB.type;
responsesDTO.push(responseDTO);
console.log({responseDTO});
}
return responsesDTO;
}
getResponsesDTO().then(responsesDTO => {
console.log(responsesDTO);
});

Erro: 404 Bad request Mongo, Express, Angular, Node

I have a problem I can not solve, my application is returning the error 400 bad request, where I can not do any post, but using the postman it works normally I can do get, post, put, delete, but in my application does not Make it possible to do the post, I have done and redid the code several times and the problem is not remedied, I need to solve this
My Controller
angular.module('primeiraApp').controller('CarCycleCtrl', [
'$scope',
'$http',
'$location',
'msgs',
'tabs',
'consts',
CarCycleController
])
function CarCycleController($scope, $http, $location, msgs, tabs, consts) {
$scope.getCarCycles = function() {
const page = parseInt($location.search().page) || 1
const url = `${consts.apiUrl}/carCycles?skip=${(page - 1) * 10}&limit=10`
$http.get(url).then(function(resp) {
$scope.carCycles = resp.data
$scope.carCycle = {}
initCarsAndOuts()
$http.get(`${consts.apiUrl}/carCycles/count`).then(function(resp) {
$scope.pages = Math.ceil(resp.data.value / 10)
tabs.show($scope, {tabList: true, tabCreate: true})
})
})
}
$scope.createCarCycle = function(){
const url = `${consts.apiUrl}/carCycles`;
$http.post(url,$scope.carCycle).then(function(response){
$scope.carCycle = {}
initCarsAndOuts()
$scope.getCarCycles()
msgs.addSuccess('Operação realizada com sucesso!')
}).catch(function(resp){
msgs.addError(resp.data.errors)
})
}
$scope.showTabUpdate = function(carCycle) {
$scope.carCycle = carCycle
initCarsAndOuts()
tabs.show($scope, {tabUpdate: true})
}
$scope.updateCarCycle = function() {
const url = `${consts.apiUrl}/carCycles/${$scope.carCycle._id}`
$http.put(url, $scope.carCycle).then(function(response) {
$scope.carCycle = {}
initCarsAndOuts()
$scope.getCarCycles()
tabs.show($scope, {tabList: true, tabCreate: true})
msgs.addSuccess('Operação realizada com sucesso!')
}).catch(function(resp) {
msgs.addError(resp.data.errors)
})
}
$scope.showTabDelete = function(carCycle) {
$scope.carCycle = carCycle
initCarsAndOuts()
tabs.show($scope, {tabDelete: true})
}
$scope.deleteCarCycle = function() {
const url = `${consts.apiUrl}/carCycles/${$scope.carCycle._id}`
$http.delete(url, $scope.carCycle).then(function(response) {
$scope.carCycle = {}
initCarsAndOuts()
$scope.getCarCycles()
tabs.show($scope, {tabList: true, tabCreate: true})
msgs.addSuccess('Operação realizada com sucesso!')
}).catch(function(resp) {
msgs.addError(resp.data)
})
}
$scope.addDebt = function(index) {
$scope.carCycle.outs.splice(index + 1, 0, {})
}
$scope.cloneDebt = function(index, {name, value, status}) {
$scope.carCycle.outs.splice(index + 1, 0, {name, value, status})
initCarsAndOuts()
}
$scope.deleteDebt = function(index) {
$scope.carCycle.outs.splice(index, 1)
initCarsAndOuts()
}
$scope.addCredit = function(index) {
$scope.carCycle.cars.splice(index + 1, 0, {name: null, value: null})
}
$scope.cloneCredit = function(index, {name, value}) {
$scope.carCycle.cars.splice(index + 1, 0, {name, value})
initCarsAndOuts()
}
$scope.deleteCredit = function(index) {
$scope.carCycle.cars.splice(index, 1)
initCarsAndOuts()
}
$scope.cancel = function() {
tabs.show($scope, {tabList: true, tabCreate: true})
$scope.carCycle = {}
initCarsAndOuts()
}
$scope.calculateValues = function() {
$scope.car = 0
$scope.out = 0
if($scope.carCycle) {
$scope.carCycle.cars.forEach(function({value}) {
$scope.car += !value || isNaN(value) ? 0 : parseFloat(value)
})
$scope.carCycle.outs.forEach(function({value}) {
$scope.out += !value || isNaN(value) ? 0 : parseFloat(value)
})
}
$scope.total = $scope.car - $scope.out
}
var initCarsAndOuts = function() {
if(!$scope.carCycle.outs || !$scope.carCycle.outs.length) {
$scope.carCycle.outs = []
$scope.carCycle.outs.push({})
}
if(!$scope.carCycle.cars || !$scope.carCycle.cars.length) {
$scope.carCycle.cars = []
$scope.carCycle.cars.push({})
}
$scope.calculateValues()
}
$scope.getCarCycles()
}
My Backend
const _ = require('lodash')
const CarCycle = require('./carCycle')
CarCycle.methods(['get', 'post', 'put', 'delete'])
CarCycle.updateOptions({new: true, runValidators: true})
CarCycle.after('post', sendErrorsOrNext).after('put', sendErrorsOrNext)
function sendErrorsOrNext(err, req, res, next) {
const bundle = res.locals.bundle
if(bundle.errors) {
var errors = parseErrors(bundle.errors)
res.status(500).json({errors})
} else {
next()
}
}
function parseErrors(nodeRestfulErrors) {
const errors = []
_.forIn(nodeRestfulErrors, error => errors.push(error.message))
return errors
}
CarCycle.route('count', function(req, res, next) {
CarCycle.count(function(error, value) {
if(error) {
res.status(500).json({errors: [error]})
} else {
res.json({value})
}
})
})
module.exports = CarCycle

Resources