How to join Prompt with SetTimeout - javascript

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

Related

Regex test method returning more than a specific string [closed]

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);

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}`);
}
}
});
}
}

Json to csv dynamic columns 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, "");

Replace several strings using an array

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);

javascript regex help

I have this complex question from my customer, I can't find a answer on it so now I will try to ask you guys.
The quest is the following:
I think that one rule might be: Dots
which appears immediately after a
number, not counted as sentences. This
means that sentence present in the
"8. marts"and "2.567" is not counted as
word dots. In return, each word dots
may be overlooked (if now a sentence
ends with a number: "Vi kommer kl. 8")
but it's probably after all not quite
as often.
Another might be: If there is one
character (a letter or number)
immediately after a sentence is not a
phrase sentence. That would make that
we avoided counting the sentence
present in the "f.eks.", "bl.a."
and "cand.mag.".
I hope I can be helped here.
My code:
<script>
function word_count(field, count) {
var wordsNumberOverSeven = 0;
var wordsNumber = 0
var contentText = $(\'#lix_word_count\').val();
contentText = contentText.replace(\'?\', \'.\');
contentText = contentText.replace(\'!\', \'.\');
contentText = contentText.replace(\',\', \'\');
contentText = contentText.replace(\';\', \'\');
contentText = contentText.replace(\':\', \'\');
contentText = contentText.replace(\'\n\', \' \').replace(/^\s+|\s+$/g,\'\').replace(/\s\s+/g,\' \');
var matchDots = contentText.split(\'.\').length-1;
var match = contentText.split(\' \');
$.each(match, function(){
if ( this.length > 0 )
wordsNumber += 1;
if ( this.length >= 7 )
{
wordsNumberOverSeven += 1;
}
});
var lixMatWords = wordsNumber / matchDots;
var lixMatLongWords = ( wordsNumberOverSeven * 100 ) / wordsNumber;
var lixMatch = Math.round(( lixMatWords + lixMatLongWords ) *100)/100;
var lixType = \'\';
if ( lixMatch <= 24 )
lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er meget let at læse.\';
else if ( lixMatch <= 34 )
lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er let at læse\';
else if ( lixMatch <= 44 )
lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten ligger i midterområdet.\';
else if ( lixMatch <= 54 )
lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er svær at læse.\';
else
lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er meget svær at læse.\';
/** alert(lixType +\'\nDots: \'+ matchDots +\'\nWords: \'+ wordsNumber +\'\nLangeord: \'+ wordsNumberOverSeven); **/
alert(lixType);
}
</script>
I think we need to see the rest of the rules, or a few more at least.
Perhaps it would be better to describe what you want to include as a sentence, rather than what to exclude. If you are looking for full sentences, then it might be a period preceded by a non-whitespace character and followed by a space or new line or line feed, or some more complex rule set. It may require more than one regular expression with some other logic to sort the more complex cases.
If you want to split sentences based on that rule, then something like
mySentences.match(/(?:[^.0-9]|[0-9]+\.?|\.[a-z0-9])+(?:\.|$)/ig)
should do it.
You'll have to expand a-z to include accented characters in your language, but that should do it.
It produces the following for your input text.
["I think that one rule might be: Dots which appears immediately after a number, not counted as sentences.",
" This means that sentence present in the \"8. marts\"and \"2.567\" is not counted as word dots.",
" In return, each word dots may be overlooked (if now a sentence ends with a number: \"Vi kommer kl.",
" 8\") but it's probably after all not quite as often.",
"\n\nAnother might be: If there is one character (a letter or number) immediately after a sentence is not a phrase sentence.",
" That would make that we avoided counting the sentence present in the \"f.eks.",
"\", \"bl.a.","\" and \"cand.mag.",
"\"."]
so obviously it has trouble with dots that appear inside quoted sections. You could fix that up by walking and rejoining as long as a sentence ends inside a quoted section.
// Given mySentences defined above, walk counting quote characters.
// You could modify the regexp below if your language tends to use
// a different quoting style, e.g. French-style angle quotes.
for (var i = 0; i < mySentences.length - 1; ++i) {
var quotes = mySentences[i].match(/["\u201c\u201d]/g);
// If there are an odd number of quotes, combine the next sentence
// into this one.
if (quotes && quotes.length % 2) {
// In English, it is common to end the quoted section after the
// closing punctuator: Say "hello."
var next = mySentences[i + 1];
if (/^["\u201c\u201d]/.test(next)) {
mySentences[i] += next.substring(0, 1);
mySentences[i + 1] = next.substring(1);
} else {
mySentences[i] += next;
mySentences.splice(i, 1);
--i; // See if there's more to combine into this sentence.
}
}
}
This kind of stuff is pretty brittle though. If you want to know how it's done by people who specialize in this kind of thing, search for "natural language segmentation."

Categories

Resources