Json to csv dynamic columns javascript - javascript

I have a array of objects and i need to convert to a csv, but those objects has dynamics keys, i already create my csv columns using the object with the greater amount of keys ,now i need that if a row doesnt have the atribute the column must be empty.
My current aproach:
let output = [{
"De 0 a 10, qual a chance de você RECOMENDAR o Compass?": "7",
"De 0 a 10, que nota atribui à QUALIDADE do Compass": "8",
"Alguns destes itens já apresentou defeito?": "Painel do Motorista.",
"Pergunta teste insertção dinâmica": "Painel do Motorista"
},
{
"De 0 a 10, qual a chance de você RECOMENDAR o Compass?": "7",
"De 0 a 10, que nota atribui à QUALIDADE do Compass": "8",
"Test Question":"foo",
"Alguns destes itens já apresentou defeito?": "Painel do Motorista.",
"Test 2 Question":"bar",
"Pergunta teste insertção dinâmica": "Painel do Motorista",
}]
let key = 0;
let max = 0;
output.forEach(function(v, k) {
if (max < +Object.keys(v).length) {
max = +Object.keys(v).length;
key = k;
}
});
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += [
Object.keys(output[key]).join(";"),
...output.map(item => {
console.log(item)
console.log( Object.values(item).join(";"))
;
})
]
.join("\n")
.replace(/(^\[)|(\]$)/gm, "");
const csv = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", csv);
link.setAttribute("download", "export.csv");
link.click();
},
Current CSV output:
De 0 a 10 qual a chance de você RECOMENDAR o Compass?,De 0 a 10 que nota atribui à QUALIDADE do Compass,Test Question,Alguns destes itens já apresentou defeito?,Test 2 Question,Pergunta teste insertção dinâmica
7,8,Painel do Motorista,Painel do Motorista,Painel do Motorista,Painel do Motorista
5,5,foo,Painel do Motorista,bar,Painel do Motorista
Desired CSV output (if object doesnt have property the column must be empty):
De 0 a 10 qual a chance de você RECOMENDAR o Compass?,De 0 a 10 que nota atribui à QUALIDADE do Compass,Test Question,Alguns destes itens já apresentou defeito?,Test 2 Question,Pergunta teste inserção dinâmica.
7,8,,Painel do Motorista,,Painel do Motorista
5,5,foo,Painel do Motorista,bar,Painel do Motorista
Appreciate any help, thanks in advance.

I see in your function:
console.log( Object.values(item).join(";"))
you just join all the existing values of item. Try to map it with keys:
console.log(Object.keys(output[key]).map(it => item[it] || '').join(";"))
This will iterate through existing composed headers for the csv, retrieve value if exist and add empty string otherwise
Also do not forget return valu from ...output.map(): currently it contains only console.log operations
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += [
Object.keys(output[key]).join(";"),
...output.map(item => {
return Object.keys(output[key]).map(it => item[it] || '').join(";");
})
]
.join("\n")
.replace(/(^\[)|(\]$)/gm, "");

Related

Tip/give command economy discord.js v13

Help. So my tip/give economy command is not working very well.
The structure is
!tip user 10
There is a single space between "user" and 10 but if someone put another space like
!tip user 10
The db will crash and the economy will be null! Help, how i can fix that?
let Discord = require('discord.js')
const db = require("quick.db")
module.exports = {
name: "tip",
aliases: ['give'],
async run(client, message, args) { let currency = "yeni" //your currency
let number = message.content.substring(10)
let amount = parseInt(number.split(" ")[1])
if(amount == null) return message.reply("Ceva nu a mers bine. Încearcă din nou!")
let EASPORTS = message.mentions.members.first()
if (!EASPORTS) return message.channel.send(`**${message.author.username}** menționează pe cineva!`)
let currentWallet = await db.get(`wallet_${message.author.id}`)
let currentWallet2 = await db.get(`wallet_${EASPORTS.id}`)
if (currentWallet < amount) return message.channel.send(`**Nu ai suficienți yeni!**`)
else if (amount <= 5) return message.channel.send(`**Nu poți da ${amount}${currency} cuiva!**`)
else if (isNaN(args[1])) return message.channel.send('Pune un număr valid! n\ **Structura comenzii: !tip #mihaitza 78**');
else {
db.set(`wallet_${message.author.id}`, currentWallet - amount)
db.set(`wallet_${EASPORTS.id}`, currentWallet2 + amount)
message.channel.send(`**${message.author.username}**, ai dat ${amount} ${currency} lui **${EASPORTS.user.username}** *iar suma de yeni rămasă pe care o mai ai este ${currentWallet - amount} ${currency}*`)
}
}
}
/**
* #param { db } async [ exports ] => {
* node .
* }
*/
That's the only problem. When someone put another space between user and number,the db crash to NaN.

Javascript Loop through JSON and extract the selected data

Currently I have a JSON from which I want to extract certain specific data, for example I want to extract the
ID - Username - IP
Object from the JSON
Currently I have been trying with this code but it is not giving me the adequate results
var json = '42["getUsers",{"1620552418669":{"role":"guest","image":"/img/avatars/m/3.svg","startRoom":0,"expired":false,"free":false,"entries":"255042500","streamName":1620552397,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"MX","webmasterid":1,"id":1620552418669,"username":"luis fdo5544","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"47","name":"Más de 40","description":"La sala para mayores de 40 años.","welcome":"","date":"2019-12-07 16:12:02","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":67,"password":"","image":"/upload/rooms/2tjdhjliih0ks0wggg.jpg","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"150","reservedToGenderid":"0","orderRoom":"86","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"298","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":1457712961,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","gotBackground":true,"roomsIn":[49,48,47],"rouletteBusy":true,"socketid":"VCqjrZXOyygqHUJIBcQO","ip":2806,"password":"","email":""},"1620555811311":{"role":"guest","image":"/img/avatars/m/18.svg","startRoom":0,"expired":false,"free":false,"entries":"255043519","streamName":1620555757,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"SE","webmasterid":1,"id":1620555811311,"username":"xhip","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"48","name":"Más de 50","description":"La sala para mayores de 50 años.","welcome":"","date":"2019-12-07 16:12:30","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":1,"password":"","image":"/upload/rooms/s7eqp5bzxn4844c844.png","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"115","reservedToGenderid":"0","orderRoom":"84","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"234","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":-1200890177,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","rouletteBusy":true,"socketid":"mOPdOA1S2QDKozzKBcju","ip":3113473371,"roomsIn":[48],"password":"","email":""}},"48"]';
var parsed = JSON.parse(json.substr(2, json.length));
var newjson = (parsed);
newjson.forEach((obj) => {
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} - ${value}`);
}
});
Does anyone know how I can correct the code and get the expected results?.
Thanks.
You should be accessing the inner element of the parsed array first and from there extract the property you want.
var json = '42["getUsers",{"1620552418669":{"role":"guest","image":"/img/avatars/m/3.svg","startRoom":0,"expired":false,"free":false,"entries":"255042500","streamName":1620552397,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"MX","webmasterid":1,"id":1620552418669,"username":"luis fdo5544","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"47","name":"Más de 40","description":"La sala para mayores de 40 años.","welcome":"","date":"2019-12-07 16:12:02","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":67,"password":"","image":"/upload/rooms/2tjdhjliih0ks0wggg.jpg","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"150","reservedToGenderid":"0","orderRoom":"86","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"298","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":1457712961,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","gotBackground":true,"roomsIn":[49,48,47],"rouletteBusy":true,"socketid":"VCqjrZXOyygqHUJIBcQO","ip":2806,"password":"","email":""},"1620555811311":{"role":"guest","image":"/img/avatars/m/18.svg","startRoom":0,"expired":false,"free":false,"entries":"255043519","streamName":1620555757,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"SE","webmasterid":1,"id":1620555811311,"username":"xhip","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"48","name":"Más de 50","description":"La sala para mayores de 50 años.","welcome":"","date":"2019-12-07 16:12:30","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":1,"password":"","image":"/upload/rooms/s7eqp5bzxn4844c844.png","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"115","reservedToGenderid":"0","orderRoom":"84","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"234","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":-1200890177,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","rouletteBusy":true,"socketid":"mOPdOA1S2QDKozzKBcju","ip":3113473371,"roomsIn":[48],"password":"","email":""}},"48"]';
var parsed = JSON.parse(json.substr(2, json.length));
var obj = parsed[1]
var extracted = Object.keys(obj).map(key => {
const { id, username, ip } = obj[key]
return { id, username, ip };
})
console.log(extracted);
You can get the user objects as an array using Object.values(parsed[1])
var json = getString();
var parsed = JSON.parse(json.substr(2, json.length));
const users = Object.values(parsed[1]).map(({id,username,ip })=>({id,username,ip}))
console.log(users)
function getString(){
return '42["getUsers",{"1620552418669":{"role":"guest","image":"/img/avatars/m/3.svg","startRoom":0,"expired":false,"free":false,"entries":"255042500","streamName":1620552397,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"MX","webmasterid":1,"id":1620552418669,"username":"luis fdo5544","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"47","name":"Más de 40","description":"La sala para mayores de 40 años.","welcome":"","date":"2019-12-07 16:12:02","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":67,"password":"","image":"/upload/rooms/2tjdhjliih0ks0wggg.jpg","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"150","reservedToGenderid":"0","orderRoom":"86","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"298","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":1457712961,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","gotBackground":true,"roomsIn":[49,48,47],"rouletteBusy":true,"socketid":"VCqjrZXOyygqHUJIBcQO","ip":2806,"password":"","email":""},"1620555811311":{"role":"guest","image":"/img/avatars/m/18.svg","startRoom":0,"expired":false,"free":false,"entries":"255043519","streamName":1620555757,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"SE","webmasterid":1,"id":1620555811311,"username":"xhip","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"48","name":"Más de 50","description":"La sala para mayores de 50 años.","welcome":"","date":"2019-12-07 16:12:30","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":1,"password":"","image":"/upload/rooms/s7eqp5bzxn4844c844.png","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"115","reservedToGenderid":"0","orderRoom":"84","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"234","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":-1200890177,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","rouletteBusy":true,"socketid":"mOPdOA1S2QDKozzKBcju","ip":3113473371,"roomsIn":[48],"password":"","email":""}},"48"]';
}
In your implementation what you are getting after parsing is an array, and the required fields such as id, username & ip are present in the object present at index 1 of the parsed string.
Since the value present at index 1 is an object we can make use of Object.keys or Object.values or Object.entries as per the need. In the below example I've used Object.values to get the required output.
const json = '42["getUsers",{"1620552418669":{"role":"guest","image":"/img/avatars/m/3.svg","startRoom":0,"expired":false,"free":false,"entries":"255042500","streamName":1620552397,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"MX","webmasterid":1,"id":1620552418669,"username":"luis fdo5544","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"47","name":"Más de 40","description":"La sala para mayores de 40 años.","welcome":"","date":"2019-12-07 16:12:02","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":67,"password":"","image":"/upload/rooms/2tjdhjliih0ks0wggg.jpg","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"150","reservedToGenderid":"0","orderRoom":"86","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"298","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":1457712961,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","gotBackground":true,"roomsIn":[49,48,47],"rouletteBusy":true,"socketid":"VCqjrZXOyygqHUJIBcQO","ip":2806,"password":"","email":""},"1620555811311":{"role":"guest","image":"/img/avatars/m/18.svg","startRoom":0,"expired":false,"free":false,"entries":"255043519","streamName":1620555757,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"SE","webmasterid":1,"id":1620555811311,"username":"xhip","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"48","name":"Más de 50","description":"La sala para mayores de 50 años.","welcome":"","date":"2019-12-07 16:12:30","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":1,"password":"","image":"/upload/rooms/s7eqp5bzxn4844c844.png","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"115","reservedToGenderid":"0","orderRoom":"84","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"234","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":-1200890177,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","rouletteBusy":true,"socketid":"mOPdOA1S2QDKozzKBcju","ip":3113473371,"roomsIn":[48],"password":"","email":""}},"48"]';
const parsed = JSON.parse(json.substr(2, json.length));
const newjson = parsed[1];
Object.values(newjson).forEach(valueObj => {
const { id, ip, username } = valueObj;
console.log(`id: ${id}`);
console.log(`username: ${username}`);
console.log(`ip: ${id}`);
});
For a more dynamic version, if you want to pass the keys for which you want to get the data we can use the below method.
var json = '42["getUsers",{"1620552418669":{"role":"guest","image":"/img/avatars/m/3.svg","startRoom":0,"expired":false,"free":false,"entries":"255042500","streamName":1620552397,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"MX","webmasterid":1,"id":1620552418669,"username":"luis fdo5544","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"47","name":"Más de 40","description":"La sala para mayores de 40 años.","welcome":"","date":"2019-12-07 16:12:02","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":67,"password":"","image":"/upload/rooms/2tjdhjliih0ks0wggg.jpg","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"150","reservedToGenderid":"0","orderRoom":"86","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"298","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":1457712961,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","gotBackground":true,"roomsIn":[49,48,47],"rouletteBusy":true,"socketid":"VCqjrZXOyygqHUJIBcQO","ip":2806,"password":"","email":""},"1620555811311":{"role":"guest","image":"/img/avatars/m/18.svg","startRoom":0,"expired":false,"free":false,"entries":"255043519","streamName":1620555757,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"SE","webmasterid":1,"id":1620555811311,"username":"xhip","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"48","name":"Más de 50","description":"La sala para mayores de 50 años.","welcome":"","date":"2019-12-07 16:12:30","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":1,"password":"","image":"/upload/rooms/s7eqp5bzxn4844c844.png","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"115","reservedToGenderid":"0","orderRoom":"84","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"234","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":-1200890177,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","rouletteBusy":true,"socketid":"mOPdOA1S2QDKozzKBcju","ip":3113473371,"roomsIn":[48],"password":"","email":""}},"48"]';
const parsed = JSON.parse(json.substr(2, json.length));
const newjson = parsed[1];
const getValues = (dataObj, keys) => Object.values(dataObj).map(valueObj => {
const obj = {}
keys.forEach(key => {
obj[key] = valueObj[key];
});
return obj;
});
console.log(getValues(newjson, ["id", "username", "ip"]));
You may try this one.
var json =
'42["getUsers",{"1620552418669":{"role":"guest","image":"/img/avatars/m/3.svg","startRoom":0,"expired":false,"free":false,"entries":"255042500","streamName":1620552397,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"MX","webmasterid":1,"id":1620552418669,"username":"luis fdo5544","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"47","name":"Más de 40","description":"La sala para mayores de 40 años.","welcome":"","date":"2019-12-07 16:12:02","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":67,"password":"","image":"/upload/rooms/2tjdhjliih0ks0wggg.jpg","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"150","reservedToGenderid":"0","orderRoom":"86","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"298","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":1457712961,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","gotBackground":true,"roomsIn":[49,48,47],"rouletteBusy":true,"socketid":"VCqjrZXOyygqHUJIBcQO","ip":2806,"password":"","email":""},"1620555811311":{"role":"guest","image":"/img/avatars/m/18.svg","startRoom":0,"expired":false,"free":false,"entries":"255043519","streamName":1620555757,"roles":{"canKick":"0","canBan":"0","canMute":false,"canSpyWhisperMessages":"0","canDeleteUserMessages":"0"},"country":"SE","webmasterid":1,"id":1620555811311,"username":"xhip","isGuest":true,"gender":"hombre","hasFlash":false,"hasWebcam":false,"hasWebrtc":true,"room":{"id":"48","name":"Más de 50","description":"La sala para mayores de 50 años.","welcome":"","date":"2019-12-07 16:12:30","destructionDate":"0000-00-00 00:00:00","webmasterid":"1","users":1,"password":"","image":"/upload/rooms/s7eqp5bzxn4844c844.png","default":"0","webcam":"0","colorPicker":"1","isTemporary":"0","ownerid":"0","maxUsers":"115","reservedToGenderid":"0","orderRoom":"84","inPrivateConference":"0","isAdult":"0","reservedToRoles":"0","tags":"","country":"","numberFavorit":"234","approved":"0","deleted":"0","reservedToGenderidCondition":"Equals","reservedToRolesCondition":"Equals","urlImage":"","isHidden":"0","radio_url":"","radio_start":"1"},"webcam":false,"status":"online","webcamPublic":false,"privateOnlyOnInvitation":true,"credits":0,"e":"","isMobile":false,"fingerprint":-1200890177,"enterChatMode":true,"friends":{},"doNotAcceptPrivate":true,"myFavouriteRooms":[],"oldRole":"guest","rouletteBusy":true,"socketid":"mOPdOA1S2QDKozzKBcju","ip":3113473371,"roomsIn":[48],"password":"","email":""}},"48"]';
var parsed = JSON.parse(json.substr(2, json.length));
var newjson = parsed;
for (const key in newjson) {
if (Object.hasOwnProperty.call(newjson, key)) {
const element = newjson[key];
var keys = Object.keys(element);
keys.forEach((el) => {
if (Object.hasOwnProperty.call(element[el], "role")) {
for (const [key, value] of Object.entries(element[el])) {
console.log(`${key} - ${value}`);
}
}
});
}
}

Use Regex to fetch data

The regex I have made fetches itemlist from opts.taskDetails.order_details.
I want to optimize the regex/any other better regex to get the following data as is shown in the above image.
(which can be 1 item list or multiple).
Also apart from fetching the item details I also want to fetch data which is left after fetching items list from opts.taskDetails.order_details below.
Tipo de papa: -\nPapa Amarilla Tumbay S/0.00\n Adicional : - Quesp cheddar S/0.00\n Agrega Bebida: - Fanta 400 ml S/0.00\n
Salsas: - Mayonesa S/0.00\n - Ketchup S/0.00\n - Golf S/0.00\n - Guacamole S/0.00\n - Ají S/0.00\n - Tártara S/0.00\n - Mayo-aji S/0.00\n
CODE
var opts = {
"items": [{
"mail_parser_label": "order_details",
"label": "order_details",
"data_type": "Table",
"app_side": "0",
"required": 0,
"value": 1,
"data": {
"head": [{
"mail_parser_label": "Detalle",
"label": "Detalle",
"type": "text",
"arth": " ",
"id": 0,
"show": 1,
"app_side": 0,
"required": 0
}, {
"mail_parser_label": "Cantidad",
"label": "Cantidad",
"type": "text",
"arth": " ",
"id": 1,
"show": 1,
"app_side": 0,
"required": 0
}, {
"mail_parser_label": "Unidad",
"label": "Unidad",
"type": "text",
"arth": " ",
"id": 2,
"show": 1,
"app_side": 0,
"required": 0
}, {
"mail_parser_label": "Total",
"label": "Total",
"type": "text",
"arth": " ",
"id": 2,
"show": 1,
"app_side": 0,
"required": 0
}],
"other": [],
"body": []
},
"template_id": "NUEVO_PEDIDO",
"appCheck": true
}],
"taskDetails": {
"order_details":"Detalle\n Unidad\n Cantidad\n Total\n Triple Insomnio Especial S/37.90 1 S/37.90 Insomnio Especial \nS/212 S/23.12 *Tipo de papa:* - Papa Amarilla Tumbay S/0.00\n *Adicional :* - Quesp cheddar S/0.00\n *Agrega Bebida:* - Fanta 400 ml S/0.00\n *Salsas:* - Mayonesa S/0.00\n - Ketchup S/0.00\n - Golf S/0.00\n - Guacamole S/0.00\n - Ají S/0.00\n - Tártara S/0.00\n - Mayo-aji S/0.00\n   "
}
}
var items = opts.items;
var taskDetails = opts.taskDetails;
for (var p = 0; p < items.length; p++) {
var parameter = items[p];
if (parameter.mail_parser_label == "order_details") {
var str = taskDetails.order_details.toString().replace(/[ ]+/g, ' ');
var itemPatternFull = str.match(/[A-Za-z0-9 ]*S\/\d{1,}[.]*\d*\s+\d{1,}\s+S\/\d{1,}[.]*\d*/g);
var itemPattern = itemPatternFull ? itemPatternFull.toString().match(/S\/\d{1,}[.]*\d*\s+\d{1,}\s+S\/\d{1,}[.]*\d*/g) : [];
var details = itemPatternFull ? itemPatternFull.toString().replace(/S\/\d{1,}[.]*\d*\s+\d{1,}\s+S\/\d{1,}[.]*\d*/g, '').toString().split(',') : [];
var itemPatternLength = str.match(/S\/\d{1,}[.]*\d*\s+\d{1,}\s+S\/\d{1,}[.]*\d*/g).length;
var itemPattern = str.match(/S\/\d{1,}[.]*\d*\s+\d{1,}\s+S\/\d{1,}[.]*\d*/g);
var itemPatternArray = itemPattern.toString().replace(',', ' ').split(' ');
str = str.split(' ');
var count = 0;
if (itemPatternArray.length < str.length && details.length == itemPatternArray.length / 3) {
for (columnIndex = 0; columnIndex < itemPatternArray.length; columnIndex++) {
if (columnIndex % 3 == 0) {
parameter.data.body.push({
"val": details[count].trim(),
"id": count + columnIndex,
"head": "Dettalle"
});
count++;
}
parameter.data.body.push({
"val": itemPatternArray[columnIndex].replace(/S\//, ''),
"id": columnIndex + count,
"head": str[(columnIndex % 3) + 1] ? str[(columnIndex % 3) + 1].toString().replace('\n', '') : str[(columnIndex % 3) + 1]
});
}
}
} else {
parameter.data = taskDetails[parameter.mail_parser_label].toString().trim().replace(/[\s+\n]/g, ' ');
}
}
console.log("ITEMS", parameter.data.body)
Here is a regex to chop up your order_details and also extract the remainder at the end.
I used one rx to get header, items, and extras. Then another to parse the items using the g flag. You can validate even more, either in the regex, or parsing the match into a number, but you should get the point. The key is 2 phase parsing.
I put the results in an order object. You can simply map that to whatever you want; It was easier to show the regex and solution isolated from your other code.
var order_details = `Detalle\n Unidad\n Cantidad\n Total\n Triple Insomnio Especial S/37.90 1 S/37.90 Insomnio Especial \nS/23.12 1 S/23.12 Tipo de papa: - Papa Amarilla Tumbay S/0.00\n Adicional : - Quesp cheddar S/0.00\n Agrega Bebida: - Fanta 400 ml S/0.00\n Salsas: - Mayonesa S/0.00\n - Ketchup S/0.00\n - Golf S/0.00\n - Guacamole S/0.00\n - Ají S/0.00\n - Tártara S/0.00\n - Mayo-aji S/0.00\n " `
var order_details2 = `Detalle\n Unidad\n Cantidad\n Total\n Combo Cheese Burger para 2 S/39.90 1 S/39.90 Salsas primera: -\nGolf S/0.00\n Elige tu bebida: - Coca Cola 500ml S/0.00\n Elige tu bebida: - Coca Cola 500ml S/0.00\n Verduras primera : - Cebolla blanca S/0.00\n - Tomate S/0.00\n - Lechuga S/0.00\n Salsas segunda : - Golf S/0.00\n - Tártara S/0.00\n Verduras segunda : - Cebolla blanca S/0.00\n - Tomate S/0.00\n - Lechuga S/0.00\n Porción de papa : - Papa Regular S/0.00\n`
function parse(string) {
// header, items, and tipo
var rxItems = /Detalle\n Unidad\n Cantidad\n\ Total\n\s*([^:]+)(([^:]+:[\s\S]*)) /
// single item line
var rxItem = /s*(.*?)\s+(S\/.*?)\s+(\d+)\s+(S\/.*?)/g
var order = {
items: [],
other: null
}
var mParts = rxItems.exec(string)
var items = mParts[1]
order.other = mParts[2]
var mItem = rxItem.exec(items)
while (mItem) {
var detalle = mItem[1]
var unidad = mItem[2]
var cantidad = mItem[3]
var total = mItem[4]
let item = {
detalle,
unidad,
cantidad,
total
}
order.items.push(item)
mItem = rxItem.exec(items)
}
console.log(order)
}
parse(order_details)
parse(order_details2)

How to join Prompt with SetTimeout

I am totally new to Javascript. I started my course just this week. I even don't know if we post HTML code here or not.
I have a question about delaying prompt with if statment.
I tried a lot of things shown here about alerts and confirmation, but they are not applied on prompt.
Here is my code (which is very primitive), so please show me how to delay prompt, with an if statment .
What I want to do is: I want the user to read the choices 1st for 10 seconds before the Prompt shows up, then the prompt gives you a choice. Depending on the choice, the results changes.
<meta chartset = "utf-8">
<h1> Car </h1>
In 10 seconds, you can choose your destination BY NUMBER
<br>
Higiénopolis : 1
<br>
Santa Cécilia : 2
<br>
Vila Madalena : 3
<br>
<script>
var hi = 1
var sc = 2
var vm = 3
var dest=prompt("Choose your destination :");
if(dest==1){
document.write("<br>Your position is Caelum.")
document.write("<br>Your destination is Higiénopolis.")
document.write("<br> A distancia é : 7 km")
document.write("<br> O tempo para chegar é : 28 min")
}
if(dest==2){
document.write("<br>Your position is Caelum.")
document.write("<br>Your destination is Santa Cécilia.")
document.write("<br> A distancia é : 9,4 km")
document.write("<br> O tempo para chegar é : 31 min")
}
if(dest==3){
document.write("<br>Your position is Caelum.")
document.write("<br>Your destination is Vila Madalena.")
document.write("<br> A distancia é : 10 km")
document.write("<br> O tempo para chegar é : 35")
}
</script>
You can use setTimeout
var hi = 1
var sc = 2
var vm = 3
var dest = '';
setTimeout(function() {
dest = prompt("Choose your destination :");
if (dest == 1) {
document.write("<br>Your position is Caelum.")
document.write("<br>Your destination is Higiénopolis.")
document.write("<br> A distancia é : 7 km")
document.write("<br> O tempo para chegar é : 28 min")
}
if (dest == 2) {
document.write("<br>Your position is Caelum.")
document.write("<br>Your destination is Santa Cécilia.")
document.write("<br> A distancia é : 9,4 km")
document.write("<br> O tempo para chegar é : 31 min")
}
if (dest == 3) {
document.write("<br>Your position is Caelum.")
document.write("<br>Your destination is Vila Madalena.")
document.write("<br> A distancia é : 10 km")
document.write("<br> O tempo para chegar é : 35")
}
}, 2000)
Note : The conditional statements are also inside setTimeout, because, it is an asynchronous function.
If you want to keep it outside, put it in a different function and call that function
DEMO

I need to know if an array content is more than 0

HERE IS THE SUMMARY:
I prompt 3 value numbers for the array, if the addition total of the arrays elements are more than 0, i need to display "el funcionamiento no es infinito" otherwise "es infinito"
its not working due i think i am not calculating all element in the array danio_Total
HERE IS THE CODE, THANKS!
var comprobarTiempoFuncionamiento = function(i) {
if (danio_Total.value > 0) {
document.write("el funcionamiento no es infinito");
} else {document.write("El tiempo de funcionamiento es infinito");}
}
This is easier than it sounds, if you have an array and all you want to do is check if the sum is larger than zero, than you can reverse it and say that the sum would only be zero if all values in the array is zero (unless you have negative numbers), so this
[0,0,0,0]
would be the only type of array that would sum up to zero.
As zero's are falsy, you can just do
if ( danio_Total.filter(Boolean).length ) {
document.write("el funcionamiento no es infinito");
} else {
document.write("El tiempo de funcionamiento es infinito");
}
When filtering on Boolean, any positive integer will be truthy, so
[0,0,9].filter(Boolean).length; // returns 1, truthy
[0,3,9].filter(Boolean).length; // returns 2, truthy
[0,0,0].filter(Boolean).length; // returns 0, falsy
so it alls you really need.
Try it like bellow
var total = danio_toal.reduce(function(a,b){
return a+b;
});
if (total > 0) {
document.write("el funcionamiento no es infinito");
} else {document.write("El tiempo de funcionamiento es infinito");}
if you want know the length of array try this:
for (i = 0; i < array.length; i++){
sum += array[i];
}

Categories

Resources