2

I have the following json:

{
'a':'vala',
'b':'valb'
}

I want to convert this to a string:

"a=vala,b=valb"

What is the best way to get there?

2
  • 1
    Simple loop over the object? Commented Jul 27, 2015 at 23:01
  • Im a python guy, no array.join() type magic? Commented Jul 27, 2015 at 23:18

3 Answers 3

3

Use Object.keys to get all the keys, map over the results to format the string, and finally join using a comma separator.

var item = {
  'a':'vala',
  'b':'valb'
};

var result = Object.keys(item).map(function(key) {
    return key + '=' + item[key];
}).join(',');
Sign up to request clarification or add additional context in comments.

Comments

0

var obj = {
'a':'vala',
'b':'valb'
};

var str = '';
for (var key in obj) {
   if (str.length != 0) str += ',';
   str += key+'='+obj[key];
}

alert(str);

Comments

0

Another way you could do it--all it takes is a simple for in loop on the object with some formatting for your results:

var obj = {
  'a':'vala',
  'b':'valb'
};

function translate(obj) {
  var result = [];
  for (var key in obj) {
    result.push(key + '=' + obj[key]);
  }  
  return result.join(',')
}

console.log(translate(obj));

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.