如何将JavaScript对象属性和值转换为字符串?
示例:
{
name: "mark",
age: "20"
status: "single"
}
预期产出:
name:mark AND age:20 AND status:single
答案 0 :(得分:2)
有很多方法可以做到这一点,迭代对象属性的所有变化。 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
进一步阅读:
答案 1 :(得分:0)
这是一个有效的解决方案。希望它有所帮助!
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);