How can I convert a JavaScript object property and value into a string?
example:
{
name: "mark",
age: "20"
status: "single"
}
expected output:
name:mark AND age:20 AND status:single
How can I convert a JavaScript object property and value into a string?
example:
{
name: "mark",
age: "20"
status: "single"
}
expected output:
Share Improve this question asked Apr 11, 2017 at 3:48 Archael AnieArchael Anie 2412 silver badges12 bronze badges 4name:mark AND age:20 AND status:single
-
1
With a loop? What have you tried? Do you want to output all properties, or specifically
name
,age
, andstatus
if present? – nnnnnn Commented Apr 11, 2017 at 3:51 - I want to output like exactly the expected output :). I tried several code but did not work. – Archael Anie Commented Apr 11, 2017 at 3:53
-
Yes, and if the input was different, say,
{name:"mark",age:"20",status:"single",hobby:"bowling"}
what would the expected output be? Again, do you want all properties, or just specificallyname
,age
, andstatus
if present? – nnnnnn Commented Apr 11, 2017 at 3:55 -
the out put would be:
name:mark AND age:20 AND status:single AND hobby:bowling
. only if present :) – Archael Anie Commented Apr 11, 2017 at 3:58
2 Answers
Reset to default 5There are a number of ways to do this, all variations on iterating through the object's properties. E.g.:
function propsAsString(obj) {
return Object.keys(obj).map(function(k) { return k + ":" + obj[k] }).join(" AND ")
}
console.log(propsAsString({ name: "mark", age: "20", status: "single" }))
console.log(propsAsString({ color: "red", shape: "square" }))
console.log(propsAsString({ name: "mary" }))
console.log(propsAsString({ })) // outputs empty string
Further reading:
Object.keys()
.map()
.join()
Here's a working solution. Hope it helps!
var someObject = {
name: "mark",
age: "20",
status: "single"
}
var result = "";
var counter = 0;
for(var i in someObject){
if(counter > 0){
result += " AND ";
}
++counter;
result += i + ": "+someObject[i] + " ";
}
console.log(result);