-1

I'm a bit new to JavaScript so I want to know how I can convert something like this :

var names = "{ guy:'Henry' guy2:'Joe' guy3:'Bob' }"

from a string into an actual object and then access the values of keys. I tried to use :

names = eval(names)
console.log(names.guy)

I'd get undefined and if i try :

console.log(names)

I'd get just the first value of the object which is 'Henry' Please can someone help me with this and if my question wasn't explanatory enough, i can make it clearer

woozyking
  • 4,880
  • 1
  • 23
  • 29
  • 1
    have you looked into JSON parsing? – woozyking Feb 21 '21 at 21:09
  • 2
    @woozyking The string isn't valid JSON. It's valid JavaScript code. – Thomas Sablik Feb 21 '21 at 21:11
  • @ThomasSablik i see. then it depends on whether this pattern is consistent, a string parsing approach may be viable – woozyking Feb 21 '21 at 21:14
  • 3
    Actually this is not valid JS. Try `eval("(" + names + ")")` ... Also are there commas in it? – Jonas Wilms Feb 21 '21 at 21:17
  • 2
    Try this JSON.parse('{"guy":"Henry","guy2":"Joe","guy3":"Bob"}') – akhil regonda Feb 21 '21 at 21:17
  • Re "something like this": if you have any choice don't use a made up string format. Instead use string text written in [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON),which is a standardized way of serializing object data. If someone is forcing their made up format on you, tell them to use JSON. – traktor Feb 21 '21 at 21:24
  • 1
    This is a non standard format. It's nearly impossible to write a reliable parser without specification just with one example. You should either use a standard format like JSON or specify the format. Does your format support numbers, nested objects, spaces or arrays? – Thomas Sablik Feb 21 '21 at 22:08

2 Answers2

0

with quite a bit of assumptions, the foremost being the given string has a fixed pattern as in OP, then something like this may fit the need:

var names = "{ guy:'Henry' guy2:'Joe' guy3:'Bob' }"


names = names
  .replace(/^{/, '') // remove leading '{'
  .replace(/}$/, '') // reomve closing '}'
  .trim() // trim surrounding empty spaces
  .split(' ') // split out key:value pairs
  .map((s) => s.split(':')) // "parse" supposed key:value pairs
  .reduce((acc, [k, v]) => {
    acc[k] = eval(v) // suppose the value portion is always quoted
    return acc
  }, {})

console.log(names.guy)

but if you have the choice of the input, rather ensure that it comes in as a valid JSON string, as suggested in the comments section

woozyking
  • 4,880
  • 1
  • 23
  • 29
-1

As you mentiond your variable is a string which you can parse into an object by using let v = JSON.parse(names). You can than use console.log(names.guy) to output the value. If you wanted to cast an object to a string you could use JSON.stringify().

gogibogi4
  • 263
  • 4
  • 15