3

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

4
  • 1
    With a loop? What have you tried? Do you want to output all properties, or specifically name, age, and status if present? Commented Apr 11, 2017 at 3:51
  • I want to output like exactly the expected output :). I tried several code but did not work. 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? 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 :) Commented Apr 11, 2017 at 3:58

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! thanks a lot @nnnnnn :) you save my day! very much appreciated :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.