0

How to can get this

var myString = 'a,b';

in the following in most efficient way

var myObject = { a:1, b:1};

I need 1 to be associated with each param. Thank you.

9
  • 6
    Please take the time to read what JSON is. The first paragraph would suffice, I think. Commented Nov 7, 2012 at 16:47
  • 3
    You could try // Abrakadabra, but it might fail. Commented Nov 7, 2012 at 16:49
  • What are you asking exactly, how does what get into what? That first line is an error? You missing ""? Commented Nov 7, 2012 at 16:50
  • 2
    @jAndy booo, I wrote p00f Commented Nov 7, 2012 at 16:50
  • beating the computer works sometimes when Abrakadabra fails lol.. Commented Nov 7, 2012 at 16:51

3 Answers 3

5

Supposing your string is really defined as

var myString = 'a,b';

then you can get your object as

var obj = {};
var t = myString.split(',');
for (var i=0; i<t.length; i++) obj[t[i]] = 1;

This would make an obj just like

var obj = { a:1, b:1};

Note that I didn't get your goal so this might be useless...

A side remark :

JSON is a text format used for data exchange. There is nothing like a JSON object. { a:1, b:1} is just a plain javascript object with two properties.

If what you want is really JSON, you may do

var myJSON = JSON.stringify(obj);

Tis would be equivalent to

var myJSON = '{"a":1,"b":1}';
Sign up to request clarification or add additional context in comments.

3 Comments

this is a ridiculouse answer..., if it didn't have the last line I would have considered to even downvote :p
@jAndy Why is this ridiculous ? I does the required job (or at least the requested one).
Thank you dystroy for quick and elaborate answer. Just the script I was looking for. Sorry about the silly mistakes regarding string closure and calling object a JSON. Had a long day. Thank you, you guys are the best !!!!
1

var myString = a,b; does not do what you think it does.

What that does it set myString equal to the value of a and b as a undefined.

To do what you want to do, just write this:

var myJSON = { a:1, b:1};

and p00f, it just works.


The above was applicable before the ninja edit of the OP.

Comments

1

You can use .split() and .reduce() for this.

var result = myString.split(',')
                     .reduce(function(obj, key) {
                         return obj[key] = 1, obj;
                     }, {});

You'll need a shim for older JavaScript implementations.

2 Comments

To be more precise about the "older JavaScript implementations", this won't work with IE8 (not a critic, just a precision).
@dystroy: That's a fair clarification. I'm being lazy today.

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.