I'm using Node.js I have data like this:
const data= [
{"id":"1","date":"2022-09-07T15:56:32.279Z","req_id":"98"},
{"id":"2","date":"2022-09-08T15:48:19.075Z","req_id":"97"},
{"id":"3","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
{"id":"4","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
]
I want data in this format:
expected Output:
"2022-09-06":[
{"id":"4","date":"2022-09-06T15:48:19.073Z","req_id":"96"},
{"id":"3","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
]
"2022-09-08":[
{"id":"2","date":"2022-09-08T15:48:19.075Z","req_id":"97"}
]
"2022-09-07":[
{"id":"1","date":"2022-09-07T15:56:32.279Z","req_id":"98"}
]
Assuming the dates are always in the same format, I would do something like this:
function mapData(data){
// returns the given date as an string in the "%dd-%mm-%yyyy" format
const getDateWithoutTime = (dateString) => dateString.split("T")[0];
const mappedData = [];
for(const req of data){
const formattedDate = getDateWithoutTime(req.date);
// if the key already exists in the array, we add a new item
if(mappedData[formattedDate]) mappedData[formattedDate].push(req);
// if the key doesn't exist, we create an array with that single item for that key
else mappedData[formattedDate] = [req];
}
return mappedData;
}
Straightforward solution using regex:
let result = new Map();
for (const item of data) {
let date = item['date'].match(/\d{4}-\d{2}-\d{2}/)[0];
let items = result.get(date) || [];
items.push(item);
result.set(date, items)
}
I'm currently trying to get info off of an object but that's randomly selected. I believe that the true problem is that what I wrote is not being taken as a variable for selecting an existing object if not as the variable for the object, I don't know if this is a clear message or not.
Example of what I have tried:
let PK = ["Random1", "Random2", "Random3"]
let PKS = Math.floor(Math.random() * PK.length)
let Random1 = {
name: "Random1",
number: "010"
}
let Random2 = {
name: "Random2",
number: "011"
}
if(message.content.toLowerCase() == "random"){
message.channel.send(PK[PKS].number)
}
There is another thing I have tried which is by using ${}. These are the results:
"Random1.number" or "Random2.number" when what I was looking for is actually "010" or "011".
You should wrap your objects inside some collection such as an Array and then you just compare the value from your random selection to the value find in the collection (if any (randoms)):
let PK = ["Random1", "Random2", "Random3"];
let PKS = Math.floor(Math.random() * PK.length);
const randoms = [
{
name: "Random1",
number: "010",
},
{
name: "Random2",
number: "011",
},
];
if (message.content.toLowerCase() == "random") {
const findRandom = randoms.find((v) => v.name === PK[PKS]);
if (findRandom) {
message.channel.send(findRandom.number);
}
}
const Discord = require('discord.js')
const prefix1 = '*add'
const prefix2 = '*what'
const prefix3 = '*remove'
const prefix4 = '*search'
const bot4 = new Discord.Client();
let a = []
let fakea = []
bot4.on('message', msg => {
if(msg.member.hasPermission('ADMINISTRATOR')){
if(msg.content.startsWith(prefix1)){
let splited = msg.content.split(' ')
let unchanged = msg.content.split(' ')
splited.splice('*info', 1)
splited.splice(msg.content[1], 1)
splited.splice(msg.content[2], 1)
let c = splited.join(' ')
b = {
namer: unchanged[1],
imformation: unchanged[2],
description: c
}
if(fakea.includes(unchanged[1])){
msg.channel.send('It already exists')
} else {
a.push(b)
fakea.push(unchanged[1])
}
console.log(a)
}
if(msg.content.startsWith(prefix3)){
let armay = msg.content.split(' ')
console.log(a)
console.log(fakea)
if(armay.length != 2){
msg.channel.send(`You have either less or more than two words. That either means you wrote *add on it's own or you had more than one word that you put with the command`)
} else {
if(!fakea.includes(armay[1])){
msg.channel.send(`That doesn't exist. You can't delete something that doesn't exist.`)
} else {
let fakeafind = fakea.find(plot => plot === armay[1])
let afind = a.find(plote => plote.namer === armay[1])
fakea.splice(fakeafind, 1)
a.splice(afind, 1)
}
console.log(a)
console.log(fakea)
}
}
if(msg.content.startsWith(prefix2)){
let coolon = fakea.join('\n')
let don = `_________\n[\n${coolon}\n]\n_________`
const notbot3embed = new Discord.MessageEmbed()
.setTitle('Everything you can search')
.setColor('15DD7C')
.addField('The things you can search', don)
msg.channel.send(notbot3embed)
}
if(msg.content.startsWith(prefix4)){
let mayi = msg.content.split(' ')
if(mayi.length != 2){
msg.channel.send(`You have either less or more than two words. That either means you wrote *search on it's own or you had more than one word that you put with the command`)
} else {
if(fakea.includes(mayi[1])){
let ft = a.filter(thing => thing.namer === mayi[1])
console.log(ft)
let secot = ft.namer
let thirt = ft.imformation
let fort = ft.description
const someembed = new Discord.MessageEmbed()
.setTitle(secot)
.setColor('FF4200')
.addField(thirt, fort)
msg.channel.send(someembed)
} else {
msg.channel.send('This is not a searchable term. Use *what to see the terms that are there.')
}
}
}
}
})
bot4.login(process.env.token4)
I wrote all of it because you would be confused about the properties if I didn't. In the last part I try to get the properties of the object with the name after '*search'. Then I want to put it an embed. Here's the problem I get. On the embed all three of the things say undefined. How do I fix this
If you're confused what I'm trying to do here's what I'm trying to do. I'm trying to make a system that you can put search things(I don't know how to frase it), remove them, check which ones exist and search something. Most of it is working. But in the search part it says for all of them in the embed undefined.
I found out that you need to use find instead of filter. Find works.
im working on a Discord bot and have a reputation system with fs (npm package) and saving peoples reps in a file and doing the file name as they discord id
now im working on a top 10 command and would need some help here, i currently have this as code:
let users = [];
let reps = [];
fs.readdirSync('./data/reps/').forEach(obj => {
users.push(obj.replace('.json', ''))
let file = fs.readFileSync(`./data/reps/${obj}`)
let data = JSON.parse(file)
reps.push(data.reps)
})
let top = [...users, ...reps]
top.sort((a,b) => {a - b})
console.log(top)
the files form the users are like this:
{
"users": [
"437762415275278337"
],
"reps": 1
}
users are the current users that can't rep the persion anymore and don't need to use it in the command
i wan to get the top 10 of reps so that i can get the user id and how many reps they have, how could i do it with the code above?
You could try this
const topTen = fs.readdirSync('./data/reps/').map(obj => {
const file = fs.readFileSync(`./data/reps/${obj}`);
const data = JSON.parse(file);
return { ...data, name: obj.replace('.json', '') };
}).sort((a, b) => a.reps - b.reps).slice(0, 10);
console.log(topTen);
I would change how you push the data
const users = [];
fs.readdirSync('./data/reps/').forEach(obj => {
let file = fs.readFileSync(`./data/reps/${obj}`)
let data = JSON.parse(file)
reps.push({ reps: data.reps, id: obj.replace(".json", "") });
})
That way when you sort the array the id goes along with
//define this after the fs.readdirSync.forEach method
const top = users.sort((a,b)=> a.reps-b.reps).slice(0,10);
If you want an array of top ids
const topIds = top.map(e => e.id);
If you want a quick string of it:
const str = top.map(e => `${e.id}: ${e.reps}`).join("\n");
Also you should probably just have one or two json files, one would be the array of user id's and their reps and then the other could be of user id's and who they can't rep anymore
INPUT
[
{"Id":1,"text":"Welcome","question":"san","translation":"willkommen."},
{"Id":1,"text":"Welcome","question":"se","translation":"bienvenida"},
{"Id":1,"text":"Welcome","question":"fr","translation":"propriétaires"},
{"Id":1,"text":"ajax","question":"san","translation":"ommen."},
{"Id":1,"text":"ajax","question":"se","translation":"bienve"},
{"Id":1,"text":"ajax","question":"fr","translation":"propires"}
]
if question = san then all "san" objects will be inserted in array like and so on-
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
Question is how do i check if question=san then make one array and insert all san values in it and so on without hardcoding the question property values.
Tried looping things but how to match without hardcoding because in future question attribute can change .
question="san" will be all together in an array "se" will be all together in an array and so on.
New to this not know much about nodejs.
Tried something like this but not coming as required way
fs.readFile('./data.json', 'utf8', function (err,data) {
data = JSON.parse(data);
var array = [];
for(var i = 0; i < data.length; i++) {
var lang = data[i].language;
for(var j= 0; j< data.length; j++) {
if(lang == data[j].language){
array.push(data[j].language);
array.push(data[j].translation);
array.push(data[j].text);
}
}
}
output Required
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
I recommend you to use ES6 functions instead of for. You can separate the different processes and make the code more modular and declarative. This way you can change easily the desired output since your code is made by little pieces.
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjsjdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkoweofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfefwef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (item) => ({
text:item.text,
language: item.language,
translation:item.translation
})
// Given a type of languages ('sde'), filter the data in function of this value
const getItemsByLanguage = (language) => {
return data.filter((item) => item.language === language)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of languages: ['sde', 'ses', 'sfr', ...]
const uniqueLanguages = data.map((item) => item.language).filter(onlyUnique)
// Get all found items for a language ('sde') and get the desired format (returns array of objects)
const resultArray = uniqueLanguages.map((language) => (
{[language]: getItemsByLanguage(language).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjs
jdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk
kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkowe
ofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfef
wef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (data) => ({
text:data.text,
question: data.question,
translation:data.translation
})
// Given a type of question ('san'), filter the data in function of this value
const getQuestions = (question) => {
return data.filter((item) => item.question === question)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of questions: ['san', 'se', 'fr']
const uniqueQuestions = data.map((item) => item.question).filter(onlyUnique)
// Get all found values for a question and get the desired format (returns
array of objects)
const resultArray = uniqueQuestions.map((question) => (
{[question]: getQuestions(question).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)