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}`);
}
}
});
}
}
Related
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
I'm trying to search a specific string like 9.7 in an array using regex test method, but, it's returning values that contains 1984, 1987 in the same row and also 9.7 rows.
searchText= '9.7';
items = [ {description: "MERCEDES BENZ L 1519 - OM 355/5 9.7 L 10V SOHV L5 1973 1987"}, {description: "MERCEDES BENZ LB 2219 - OM 355/5 9.7 L 10V SOHV L5 1973 1980"}, {description: "MERCEDES BENZ LS 1932 - OM 355/6 LA 11.6 L 12V SOHV L6 1984 1987"}, {description: "MERCEDES BENZ O 370 RSD OM 355/5 11.6 L 10V SOHV L5 1985 1987"} ]
let returnArray = [],
splitText = searchText.toLowerCase().split(/\s+/),
regexp_and = '(?=.*' + splitText.join(')(?=.*') + ')',
re = new RegExp(regexp_and, 'i');
for (let x = 0; x < items.length; x++) {
if (re.test(items[x][field])) {
returnArray.push(items[x]);
}
}
return returnArray;
Expected output:
array = [ {description: "MERCEDES BENZ L 1519 - OM 355/5 9.7 L 10V SOHV L5 1973 1987"}, {description: "MERCEDES BENZ LB 2219 - OM 355/5 9.7 L 10V SOHV L5 1973 1980"}]
Could anyone help me?
Thanks.
The . is a special char meaning any character. So when your search string contains it you need to escape it or it will be treated like the wildcard.
use
const splitText = searchText
.toLowerCase()
.split(/\s+/)
.map(token=>token.replace(/\./g,'\\.'));
but keep in mind that this might happen with other special characters
const searchText = '9.7';
const items = [{
description: "MERCEDES BENZ L 1519 - OM 355/5 9.7 L 10V SOHV L5 1973 1987"
}, {
description: "MERCEDES BENZ LB 2219 - OM 355/5 9.7 L 10V SOHV L5 1973 1980"
}, {
description: "MERCEDES BENZ LS 1932 - OM 355/6 LA 11.6 L 12V SOHV L6 1984 1987"
}, {
description: "MERCEDES BENZ O 370 RSD OM 355/5 11.6 L 10V SOHV L5 1985 1987"
}];
const returnArray = [];
const splitText = searchText
.toLowerCase()
.split(/\s+/)
.map(token => token.replace(/\./g, '\\.'));
const regexp_and = '(?=.*' + splitText.join(')(?=.*') + ')';
const re = new RegExp(regexp_and, 'i');
const field = 'description';
for (let x = 0; x < items.length; x++) {
if (re.test(items[x][field])) {
returnArray.push(items[x]);
}
}
console.log(returnArray);
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, "");
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 an array to make this:
Hi {nom}, you can buy {var1}
Look like this before being sent:
Hi Manuel, you can buy chips.
I have tried to do this with an array like this:
$(document).on('click','.submitMessage', function(){
prevContent=$('textarea').val();
$variables = array(
'{nom}' => 'Manuel',
'{apl}' => 'García',
'{var1}' => 'chips',
'{var2}' => 'deportes y aventura',
'{var3}' => 'informática y tecnología',
'{cst1}' => 'Serrano, 28',
'{cst2}' => 'Plaza del carmen, 32',
'{cst3}' => 'García Luna, 15'
);
$data = prevContent;
$data = str_replace(array_keys($variables), array_values($variables), $data);
$.post('../actions/newMessage.php',{ms_content:$data});
And this is the error I get on loading the page:
You are using PHP instead of Javascript :
You can do it as below
prevContent='Hi {nom}, you can buy {var1}';
variables = {
'{nom}' : 'Manuel',
'{apl}' : 'García',
'{var1}' : 'chips',
'{var2}' : 'deportes y aventura',
'{var3}' : 'informática y tecnología',
'{cst1}' : 'Serrano, 28',
'{cst2}' : 'Plaza del carmen, 32',
'{cst3}' : 'García Luna, 15'
};
$.each(variables, function (key, value) {
prevContent = prevContent.replace(key, value);
});
console.log(prevContent);
Like this:
'Hi {nom}, you can buy {var1}'.replace(/(\{([^\}]+)\})/gi, function($0, $1, $2){
return { nom: 'Manulal', var1: 'chips' }[$2] || $1;
});
a bit explain regex101.com
/(\{([^\}]+)\})/gi
1st Capturing group (\{([^\}]+)\})
\{ matches the character { literally
2nd Capturing group ([^\}]+)
[^\}]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\} matches the character } literally
\} matches the character } literally
g modifier: global. All matches (don't return on first match)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
You are mixing jQuery and PHP, Do it like the below example:
var _str = "Hi {nom}, you can buy {var1}";
var _final = _str.replace(/\{nom\}/, 'Manuel')
.replace(/\{var1\}/, 'chips');
// _final = Hi Manuel, you can buy chips
DEMO OR Alternative:
var _str = "Hi {nom}, you can buy {var1}";
// Add as many value as you want to search and replace
var _replace = {'{nom}':'Manuel', '{var1}':'chips'};
var _final = '';
for( var i in _replace ) {
var _regx = new RegExp(i, 'g');
_final = _str.replace(_regx, _replace[i]);
}
alert(_final);
What you need to achieve could also be done using this alternative and more generic way:
// input string
var inputString = "Hi {nom}, you can buy {var1}" // or $('textarea').val();
// prepare mapping object
var mappingDetails = {
'{nom}' : 'Manuel',
'{apl}' : 'García',
'{var1}' : 'chips',
'{var2}' : 'deportes y aventura',
'{var3}' : 'informática y tecnología',
'{cst1}' : 'Serrano, 28',
'{cst2}' : 'Plaza del carmen, 32',
'{cst3}' : 'García Luna, 15'
}
// get the regex
var generatedRegex = new RegExp(Object.keys(mappingDetails).join("|"),"gi");
// replace the placeholders
inputString = inputString.replace(generatedRegex , function(matchedText){
return mappingDetails [matchedText];
});
// output
console.log(inputString);