最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert object property and values to String - Stack Overflow

programmeradmin0浏览0评论

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:

name:mark AND age:20 AND status:single

Share Improve this question asked Apr 11, 2017 at 3:48 Archael AnieArchael Anie 2412 silver badges12 bronze badges 4
  • 1 With a loop? What have you tried? Do you want to output all properties, or specifically name, age, and status 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 specifically name, age, and status 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
Add a ment  | 

2 Answers 2

Reset to default 5

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:

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

发布评论

评论列表(0)

  1. 暂无评论