Add two quotes in JavaScript
I have a code like this:
var event = {
"temperature" : 12.45,
"humidite" : 45.78,
"built" : "charone",
"fire" : "chartwo",
"topic" : "sk1_001/data"
};
var keys = Object.keys(event);
valeurs_d = "";
for (var i = 0; i < keys.length -1 ; i++)
valeurs_d += event[keys[i]] + ", ";
var str5 = ",";
var str6 = str5.concat(valeurs_d);
var valeurs = str6.substring (0, str6.length - 2); console.log(valeurs);
I want to have everything between two quotes in a variable valeurs
like this:
, '12 .45 ', '45 .78', 'charone', 'chartwo'
Or just put strings of characters between the two quotes:
, 12.45, 45.78, 'charone', 'chartwo'
I can use in my other JSON strings.
How can I do this in JavaScript?
source to share
You can check the type and add some quotes.
var event = { temperature : 12.45, humidite : 45.78, built : "charone", fire : "chartwo", topic : "sk1_001/data" },
result = ',' + Object
.keys(event)
.slice(0, -1)
.map(k => typeof event[k] === 'string' ? '\'' + event[k] + '\'' : event[k])
.join(',');
console.log(result);
source to share
Quite simply,
var event = {
"temperature" : 12.45,
"humidite" : 45.78,
"built" : "charone",
"fire" : "chartwo",
"topic" : "sk1_001/data"
};
var keys = Object.keys(event);
valeurs_d = "";
for (var i = 0; i < keys.length -1 ; i++)
valeurs_d += "\'" + event[keys[i]]+ "\'" + ", ";
var str5 = ",";
var str6 = str5.concat(valeurs_d);
var valeurs = str6.substring(0, str6.length - 2); console.log(valeurs);
Just avoid those single quotes and concatenate them with your values.
If you need double quote in your string, use "\""
instead "\'"
.
source to share
You can add quotes directly to the string you are building, for example, in this example:
var event = {
"temperature": 12.45,
"humidite": 45.78,
"built": "charone",
"fire": "chartwo",
"topic": "sk1_001/data"
};
var keys = Object.keys(event);
var valeurs_d = "";
for (var i = 0; i < keys.length - 1; i++) {
valeurs_d += "'" + event[keys[i]] + "', ";
}
console.info(valeurs_d);
source to share
If you are using the latest version of most major browsers, you can simply use Object.values()
:
var event = {
"temperature" : 12.45,
"humidite" : 45.78,
"built" : "charone",
"fire" : "chartwo",
"topic" : "sk1_001/data"
};
console.log(Object.values(event));
If you really want the numbers as lines, change the last line to console.log(Object.values(event).map(value => String(value)))
.
And if you need an initial comma, just add it: ', ' + Object.values(event).map(value => String(value))
.
source to share
If you interpret the question correctly, you can use Object.values()
, Array.prototype.join()
with a parameter "','"
, the template literal
var event = {
"temperature" : 12.45,
"humidite" : 45.78,
"built" : "charone",
"fire" : "chartwo",
"topic" : "sk1_001/data"
};
var valeurs = `",'${Object.values(event).join("','")}'"`;
console.log(valeurs);
source to share