I have an array of objects with me:
Array of objects
Now, I want to change the property name of an particular object(not the value). For ex:
My object has attribute PRODUCT NAME:'BAJAJ Brahmi Amla Hair Oil 300 ml' in my data.
Required result:
PRODUCT_NAME:'BAJAJ Brahmi Amla Hair Oil 300 ml'
So, how can I replace the space in my property to an '_'.
Language used: React.js
I tried this function but it's not working for my desired result:
const productList = () => {
for (let i = 0; i < data.length; i++) {
let obj = data[i];
console.log(obj);
Object.keys(obj).forEach((key) => {
var replacedKey = key.trim().toUpperCase().replace(/\s\s+/g, "_");
if (key !== replacedKey) {
obj[replacedKey] = obj[key];
delete obj[key];
}
});
}
};
Can somebody explain why is this not working ?
can you please change replace(/\s\s+/g, "_") to replace(" ", "_") and then try, as you can see the below code
const productList = () => {
for (let i = 0; i < data.length; i++) {
let obj = data[i];
console.log(obj);
Object.keys(obj).forEach((key) => {
var replacedKey = key.trim().toUpperCase().replace(" ", "_");
if (key !== replacedKey) {
obj[replacedKey] = obj[key];
delete obj[key];
}
});
}
};
const string = "PRODUCT NAME"
console.log(string.trim().toUpperCase().replace(" ", "_"))
My Problem is that my bot tells me when i hit the reaction of the embed message that name is undefied. I don´t know how to fix this or how i should define name. I also dont know if this code, the reactionMemberAdd part works for many roles. It would be very great if one can help me
const Discord = require("discord.js")
const fs = require("fs")
const generalrolesConfig = JSON.parse(fs.readFileSync('./configs/generalroles.json', 'utf-8'))
module.exports = client => {
//Allgemein
//Chat Nachricht um Embed aufzurufen: general :space_invader: 813828905081110568 :computer: 815181805350682655 :frame_photo: 815181807234449428
//id von member:813828905081110568 👾
//id von programmierer: 815181805350682655 💻
//id von grafiker/desginer: 815181807234449428 🖼
client.on('message', async (msg) => {
if(msg.author.bot || !msg.guild) return;
if(msg.content.startsWith('!general')) {
var args = msg.content.split(' ')
if(args.length == 7) {
var emoji1 = args[1]
var roleid1 = args[2]
var emoji2 = args[3]
var roleid2 = args[4]
var emoji3 = args[5]
var roleid3 = args[6]
var role = msg.guild.roles.cache.get((roleid1 || roleid2 || roleid3))
if(!role) {
msg.reply('Die Rolle gibt es nicht'); return
}
var generalembed = new Discord.MessageEmbed()
.setTitle("Allgemein")
.setColor("RED")
.setDescription('TEST')
var sendedMessage = await msg.channel.send(generalembed)
sendedMessage.react(emoji1).then(sendedMessage.react(emoji2)).then(sendedMessage.react(emoji3))
var toSave = {message: sendedMessage.id, emoji1: emoji1, roleid1: roleid1, emoji2: emoji2, roleid2: roleid2, emoji3: emoji3, roleid3: roleid3}
generalrolesConfig.reactions.push(toSave)
fs.writeFileSync('./configs/generalroles.json', JSON.stringify(generalrolesConfig))
} else {
msg.reply('etwas ist falsch gelaufen')
}
}
})
client.on('messageReactionAdd', (reaction, user) => {
if(reaction.message.partial) reaction.fetch()
if(reaction.partial) reaction.fetch()
if(user.bot || !reaction.message.guild) return
for (let index = 0; index < generalrolesConfig.reactions.length; index++) {
let reactionRole = generalrolesConfig.reactions[index]
if(reaction.message.id == reactionRole.message && reaction.emoji1.name == reactionRole.emoji1 && !reaction.message.guild.members.cache.get(user.id).roles.cache.has(reactionRole.roleid)) {
reaction.message.guild.members.cache.get(user.id).roles.add(reactionRole.role)
}
}
})
}
I need some help here I have a code that shows a message being updated per 2 seconds but I want a single message that replaces itself.
let channel = guild.channels.find(channel => channel.name === guilds[guild.id].digitchan);
let channel2 = guild.channels.find(channel => channel.name === guilds[guild.id].countdownchan);
if (channel && channel2) {
channel.send(embed);
scrims[guild.id] = {
timer: setTimeout(function() {
channel2.join().then(connection => {
const dispatcher = connection.playFile('./Audio/test.mp3');
console.log('dispatcher');
console.log(dispatcher == null);
dispatcher.on('end', () => {
channel2.leave();
const embed2 = new RichEmbed()
.setColor(0xc1d9ff)
.addField("message x", false);
channel.send(embed2);
scrims[guild.id].codes = true;
scrims[guild.id].codedata = {};
scrims[guild.id].playerinterval = setInterval(function() {
const embed4 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "and more";
return false;
};
})
embed4.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed4);
}, 2000);
scrims[guild.id].timer2 = setTimeout(function() {
scrims[guild.id].codes = false;
clearInterval(scrims[guild.id].playerinterval);
const embed3 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "y mas..";
return false;
};
})
embed3.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed3);
}, 1 * 60000);
});
});
}, time * 60000);
};
};
This is the discord action:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes: 3c5
Codes: 3c5
So could be some kind of message deleting before sending the same message updated again, please let me know how to do it or some kind of code changing.
Just use message.edit() to edit the message.
message.edit() on discord.js docs
I have this code...sorry for the messiness I've been at this a while:
loadAvailabilities() {
let promises = [];
let promises2 = [];
let indexi = 0;
//return new Promise((resolve, reject) => {
this.appointments = this.af.list('/appointments', { query: {
orderByChild: 'selected',
limitToFirst: 10
}});
let mapped;
this.subscription2 = this.appointments.subscribe(items => items.forEach(item => {
//promises.push(new Promise((resolve, reject) => {
console.log(item);
let userName = item.$key;
//this.availabilities = [];
for(let x in item) {
let month = x;
console.log(x + " month");
this.appointmentsMonth = this.af.list('/appointments/' + userName + '/' + month);
this.subscription3 = this.appointmentsMonth.subscribe(items => items.forEach(item => {
this.startAtKeyAvail = item.$key;
//console.log(JSON.stringify(item) + " item");
let date = new Date(item.date.day * 1000);
let today = new Date();
console.log(date.getMonth() + "==" + today.getMonth() + "&&" + date.getDate() + "==" + today.getDate());
console.log("IN LOAD AVAILABILITIES *(*((**(*(*(*(*(*(*&^^^^%^%556565656565");
if(date.getMonth() == today.getMonth() && date.getDate() == today.getDate()) {
console.log(" inside the if that checks if its today");
console.log(item.reserved.appointment + " *************appointment");
//let counter = 0;
//mapped = item.reserved.appointment.map((r) => {
//item.reserved.appointment.forEach((r, index) => {
for(let r of item.reserved.appointment) {
promises.push(new Promise((resolve, reject) => {
if(r.selected == true) {
//this.renderer.setElementStyle(this.noavail.nativeElement, 'display', 'none');
let storageRef = firebase.storage().ref().child('/settings/' + userName + '/profilepicture.png');
let obj = {'pic':"", 'salon': userName, 'time': r.time};
storageRef.getDownloadURL().then(url => {
console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
obj.pic = url;
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
}).catch((e) => {
console.log("in caught url !!!!!!!$$$$$$$!!");
obj.pic = 'assets/blankprof.png';
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
});
}
}))
}
}
}))
}
}))
//}));
Promise.all(promises).then(() => {
console.log("in load availabilities ......... ")
console.log(JSON.stringify(this.availabilities));
this.availabilities.sort(function(a,b) {
return Date.parse('01/01/2013 '+a.time) - Date.parse('01/01/2013 '+b.time);
});
console.log('*****previous******');
console.log(JSON.stringify(this.availabilities));
console.log('*****sorted********');
for(let i of this.availabilities) {
console.log(i.time + " this is itime");
let date = new Date('01/01/2013 ' + i.time);
console.log(date + " this is date in idate");
let str = date.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
console.log(str);
i.time = str;
}
});
//}))
//})
}
I can tell from the log messages that the storageRef.getDownloadURL() function happens close to the end of when my page loads...this is where the objects actually get pushed to this.availabilities (eventually used to populate a list). The code in the Promise.all .then() actually fires before anything gets pushed to this.availabilities so when the sorting happens it is an empty array and nothing gets sorted.
I used a promise inside each forEach loop. I pushed all the promises to the same array and used Promise.all(array).then(...) how it is being used above - and the promises did their job - the array is sorted because everything is happening asynchronously.
Hi i need to do this two http get...after that i need to put data in tables and show it...but unfortunately angular doesn't wait the http request. How can i do that? in this code?
Many thanks in advance.
$rootScope.chiamataUno = function() {
var authdata = Base64.encode("DEMVSINT_ADMIN" + ":" + "Password01");
$http.defaults.headers.common["Authorization"] = "Basic " + authdata;
$http.get('http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/P8BPMREST/p8/bpm/v1/queues/DV_ResponsabileBSDL/workbaskets/Responsabile BSDL/queueelements/?cp=DCMSVS_CONN1').success(function(response) {
console.log(response);
$rootScope.rispostaUno = response.queueElements;
$rootScope.risposta = response;
$rootScope.responseJSON = JSON.stringify($scope.risposta);
var newArray = [];
$rootScope.newObjectJSON = [];
$scope.newObject = [];
for(var i=0;i<response.queueElements.length;i++){
var newObject = {
//forse togliere elementi e columns
//elementi:response.queueElements[i],
caseFolderId:response.queueElements[i].caseFolderId.replace("{","").replace("}",""),
caseTaskId:response.queueElements[i].caseTaskId.replace("{","").replace("}",""),
stepName:response.queueElements[i].stepName,
columns:response.queueElements[i].columns,
DV_Caseidentifier_for_eni_OdA: response.queueElements[i].columns.DV_Caseidentifier_for_eni_OdA,
DV_EBELP_ODA: response.queueElements[i].columns.DV_EBELP_ODA,
DV_EINDT_ODA: response.queueElements[i].columns.DV_EINDT_ODA,
DV_MATNR_TXZ01_POS_ODA: response.queueElements[i].columns.DV_MATNR_TXZ01_POS_ODA,
DV_NAMECL_POS_ODA: response.queueElements[i].columns.DV_NAMECL_POS_ODA,
DV_NETPR_WAERS_POS_ODA: response.queueElements[i].columns.DV_NETPR_WAERS_POS_ODA,
DV_PEINH_POS: response.queueElements[i].columns.DV_PEINH_POS,
DV_MENGE_MEINS_POS_ODA: response.queueElements[i].columns.DV_MENGE_MEINS_POS_ODA
};
//console.log("data "+ newObject.DV_EINDT_ODA);
var dataHold = [];
if((newObject.DV_EINDT_ODA !== null) && (newObject.DV_EINDT_ODA !== "?")){
dataHold = newObject.DV_EINDT_ODA;
dataHold = dataHold.split("/");
var dataCorrect = dataHold[2] + "/" + dataHold[1] + "/" + dataHold[0];
//console.log("dataCorrect "+ dataCorrect);
}else{
dataCorrect = newObject.DV_EINDT_ODA;
}
$rootScope.newObjectJSON.push(JSON.stringify(newObject));
//console.log("rootScope.newObjectJSON " + $rootScope.newObjectJSON);
//console.log("dettaglio " + newObject.DV_MENGE_MEINS_POS_ODA + " " + newObject.stepName + " " + newObject.DV_EINDT_ODA);
//console.log("rootScope.caseFolderId " + newObject[i].caseFolderId + " "+ newObject[i].stepName);
newArray.push(newObject);
var queryOdl = "INSERT INTO Tabella_OdL_Temp (caseFolderId, caseTaskId, stepName, DV_Caseidentifier_for_eni_OdA,DV_EBELP_ODA,DV_EINDT_ODA,DV_MATNR_TXZ01_POS_ODA,DV_NAMECL_POS_ODA,DV_NETPR_WAERS_POS_ODA,DV_PEINH_POS,DV_MENGE_MEINS_POS_ODA, Approvata, Rifiutata, Archiviata) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$cordovaSQLite.execute(db, queryOdl, [newObject.caseFolderId === null ? "null" : newObject.caseFolderId.replace("{","").replace("}",""), newObject.caseTaskId === null ? "null" : newObject.caseTaskId.replace("{","").replace("}",""),newObject.stepName === null ? "null" : newObject.stepName, newObject.DV_Caseidentifier_for_eni_OdA === null ? "null" : newObject.DV_Caseidentifier_for_eni_OdA,newObject.DV_EBELP_ODA === null ? "null" : newObject.DV_EBELP_ODA, dataCorrect === null ? "null" : dataCorrect , newObject.DV_MATNR_TXZ01_POS_ODA === null ? "null" : newObject.DV_MATNR_TXZ01_POS_ODA,newObject.DV_NAMECL_POS_ODA === null ? "null" : newObject.DV_NAMECL_POS_ODA,newObject.DV_NETPR_WAERS_POS_ODA === null ? "null" : newObject.DV_NETPR_WAERS_POS_ODA,newObject.DV_PEINH_POS === null ? "null" : newObject.DV_PEINH_POS,newObject.DV_MENGE_MEINS_POS_ODA === null ? "null" : newObject.DV_MENGE_MEINS_POS_ODA, 0, 0, 0]).then(function(result) {
console.log("insert");
}, function(error) {
console.error(error);
});
}//fine for response.queueElements
//console.log(newObject[2]);
for(var j = 0; j < newArray.length; j++){
if(newArray[j].stepName !== "Item details"){
var casefolderId = newArray[j].caseFolderId.replace("{","").replace("}","");
chiamatadue.push('http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/CASEREST/v1/case/'+ casefolderId +'?TargetObjectStore=CM_DCMSVS_TGT_OBJ');
}
}
$rootScope.chiamataDueNuova();
}) .error(function(response) {
alert("ERROR");
});
}
> Blockquote
var index = 0;
$rootScope.chiamataDueNuova = function(){
if(chiamatadue.length > 0 && index < chiamatadue.length){
var authdata = Base64.encode("DEMVSINT_ADMIN" + ":" + "Password01");
$http.defaults.headers.common["Authorization"] = "Basic " + authdata;
//inserire le autorizzazioni per la chiamata
$http.get(chiamatadue[index]).success(function(result){
index = index + 1;
console.log(result);
$scope.objJ = result.Properties;
var objToInsertOnDB = {
caseFolderId: "",
DV_EBELN_ODA: "",
DV_AEDAT_ODA: "",
DV_EKGRP_EKNAM_ODA: "",
DV_NAME_ODA: "",
DV_NETPR_WAERS_ODA: "",
DV_NAME_CR: "",
DV_StatoPraticaOdA: "",
DV_Caseidentifier_for_eni_OdA: "",
DateCreated: "",
DV_Caseidentifier_for_eni_OdA: ""
};
for(var i = 0; i < $scope.objJ.length; i++){
var actualObj = $scope.objJ[i];
//Ricerco gli elementi da trasmettere nella tabella Chiamata2
if(actualObj['SymbolicName'] === 'DV_EBELN_ODA'){
objToInsertOnDB['DV_EBELN_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_AEDAT_ODA") {
objToInsertOnDB['DV_AEDAT_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_EKGRP_EKNAM_ODA") {
objToInsertOnDB['DV_EKGRP_EKNAM_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NAME_ODA") {
objToInsertOnDB['DV_NAME_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NETPR_WAERS_ODA") {
objToInsertOnDB['DV_NETPR_WAERS_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NAME_CR") {
objToInsertOnDB['DV_NAME_CR'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_StatoPraticaOdA") {
objToInsertOnDB['DV_StatoPraticaOdA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_Caseidentifier_for_eni_OdA") {
objToInsertOnDB['DV_Caseidentifier_for_eni_OdA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DateCreated") {
objToInsertOnDB['DateCreated'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_Caseidentifier_for_eni_OdA") {
objToInsertOnDB['DV_Caseidentifier_for_eni_OdA'] = actualObj['Value'];
}
}
//setto nell'oggetto il caseFolderId
objToInsertOnDB['caseFolderId'] = chiamatadue[index-1].replace("http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/CASEREST/v1/case/","").replace("?TargetObjectStore=CM_DCMSVS_TGT_OBJ","");
console.log("caseFolderId " + objToInsertOnDB.caseFolderId);
console.log("DV_AEDAT_ODA " + objToInsertOnDB['DV_AEDAT_ODA']);
console.log("DV_NAME_CR " + objToInsertOnDB['DV_NAME_CR']);
console.log("DV_StatoPraticaOdA " + objToInsertOnDB['DV_StatoPraticaOdA']);
console.log("DV_EKGRP_EKNAM_ODA " + objToInsertOnDB['DV_EKGRP_EKNAM_ODA']);
var cfId = objToInsertOnDB.caseFolderId;
var queryOdl = "INSERT INTO Tab_OdL2_Temp(caseFolderId, DateCreated, DV_Caseidentifier_for_eni_OdA, DV_EBELN_ODA, DV_AEDAT_ODA, DV_EKGRP_EKNAM_ODA, DV_NAME_ODA, DV_NETPR_WAERS_ODA, DV_NAME_CR, DV_StatoPraticaOdA, Approvata, Rifiutata, Archiviata) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
$cordovaSQLite.execute(db, queryOdl, [objToInsertOnDB.caseFolderId === null ? "null" : objToInsertOnDB.caseFolderId, objToInsertOnDB.DateCreated === null ? "null" : objToInsertOnDB.DateCreated, objToInsertOnDB.DV_Caseidentifier_for_eni_OdA === null ? "null" : objToInsertOnDB.DV_Caseidentifier_for_eni_OdA,objToInsertOnDB.DV_EBELN_ODA === null ? "null" : objToInsertOnDB.DV_EBELN_ODA, objToInsertOnDB.DV_AEDAT_ODA === null ? "null" : objToInsertOnDB.DV_AEDAT_ODA, objToInsertOnDB.DV_EKGRP_EKNAM_ODA === null ? "null" : objToInsertOnDB.DV_EKGRP_EKNAM_ODA, objToInsertOnDB.DV_NAME_ODA === null ? "null" : objToInsertOnDB.DV_NAME_ODA, objToInsertOnDB.DV_NETPR_WAERS_ODA === null ? "null" : objToInsertOnDB.DV_NETPR_WAERS_ODA, objToInsertOnDB.DV_NAME_CR === null ? "null" : objToInsertOnDB.DV_NAME_CR, objToInsertOnDB.DV_StatoPraticaOdA === null ? "null" : objToInsertOnDB.DV_StatoPraticaOdA, 0, 0, 0]).then(function(result) {
console.log("insert Tab_OdL2_Temp");
}, function(error) {
console.error(error);
});
$rootScope.chiamataDueNuova();
});//fine get
}//fine if
$http.get("/your/url").then(function(response) {
// your code that does something with the response HERE
}).catch(function(failedResponse) {
// non-200 response from your HTTP call
})
this is because $http returns a promise. As with all promises, they have a then method which is executed when the promise is resolved or rejected.
If you have more than one request and want to act when all requests are complete you can chain them using $q. See the example below:
$q.all([one.promise, two.promise, three.promise]).then(function() {
console.log("ALL INITIAL PROMISES RESOLVED");
});
var onechain = one.promise.then(success).then(success),
twochain = two.promise.then(success),
threechain = three.promise.then(success).then(success).then(success);
$q.all([onechain, twochain, threechain]).then(function() {
console.log("ALL PROMISES RESOLVED");
});