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
There 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:
name,age, andstatusif present?{name:"mark",age:"20",status:"single",hobby:"bowling"}what would the expected output be? Again, do you want all properties, or just specificallyname,age, andstatusif present?name:mark AND age:20 AND status:single AND hobby:bowling. only if present :)