-1

I am trying to figure out how to convert a string to an object. The separators are the | characters. So essentially this:

var myString = "Name, Bob | Location, Washington | Pet, Dog";

Becomes:

var myObj = {
Name: "Bob",
Location: "Washington",
Pet: "Dog"
};

Thanks in advance for any helpful input.

12
  • 1
    Nothing built-in for that, so you'll have to write the code yourself. Shouldn't be too bad, just a couple of string split functions, and looping through the results to build your new object. If you're having specific trouble in any of those steps, then you should ask those questions. Commented Aug 20, 2013 at 23:49
  • How so? Can you please elaborate? Commented Aug 20, 2013 at 23:49
  • 2
    @BryceHanscomb - the string was, but the Q was edited to fix it. Commented Aug 20, 2013 at 23:50
  • 1
    @mwilson - yes, it did (though it wasn't me) - your question showed no research which is one of the criteria for a -1. Commented Aug 20, 2013 at 23:53
  • 1
    I would also ask this: Why is your data in this [awful] format to begin with? Commented Aug 20, 2013 at 23:55

1 Answer 1

4

This will work, assuming the string is well formatted (You will need to SHIM forEach in old browsers, or replace it with a loop):

var myString = "Name, Bob | Location, Washington | Pet, Dog";

var myObj = function(){
  var result = {};
  myString.split(/\s*\|\s*/).forEach(function(el){ 
    var parts = el.split(/\s*,\s*/); result[parts[0]] = parts[1];
  });
  return result;
}();
Sign up to request clarification or add additional context in comments.

5 Comments

@mwilson You're welcome. By the way, have you considered representing your object using JSON?
Yes, I have. However, my own personal requirement (at the time being) is to avoid using JSON or JQuery until I completely understand JavaScript (to an extent). I appreciate your help!
@mwilson: JSON is JavaScript, so don’t worry about that. If you’re interested in learning about string manipulation, there are more interesting projects to pick than custom formats…
Thanks for that. I was under the impression is was something along the lines of JQuery. Unfortunately this particular question is asked by a professor (no I'm not cheating by posting this. We are allowed to use any means necessary for help since that's how it would be in real world). This one however, was a little weird and couldn't even figure out how to approach it.
@mwilson JSON is a subset of Javascript, used to describe objects and arrays in a string. For example: var myObj = {"x": 5}; is a Javascript object, but var myString = "{\"x\": 5}"; is a JSON representation of myObj, and to parse it is as simple as var mySecondObj = JSON.parse(myString);.

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.