1

I have an object I'm pulling in and I have it's value parsed and I would like to un-parse (just the value)

So I have

MyOBj = { "name" : "(JSON.stringified object)",
          "name" : "(JSON.stringified object)" }

having trouble JSON.parse'ing just the value of an object, especially more than one. Could use some insight, thanks!

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133
  • This could be a silly question.. But just to double check.. Is the key of both objects actually "name"? Or you used "name" as an example? – Aswin Ramakrishnan Mar 07 '15 at 02:11
  • @AswinRamakrishnan name is just a placeholder, it will change dynamically – ajmajmajma Mar 07 '15 at 02:12
  • Right. But it'll be different in each case, correct? For example, your real object looks something like - `{ 'key1': 'value1', 'key2': 'value2' }` as opposed to `{ 'key1': 'value1', 'key1': 'value2' }`? – Aswin Ramakrishnan Mar 07 '15 at 02:14
  • So you just want to iterate over all objects inside `myObj`? See [this question](http://stackoverflow.com/questions/684672/loop-through-javascript-object?rq=1). – Ja͢ck Mar 07 '15 at 02:16

2 Answers2

2

If you use Underscore, you can simply use the Values helper to return an array of all the values in your object.


Option 1: Use Underscore

From Underscore Documentation -> Underscore: Object, Values

values_.values(object)
Return all of the values of the object's own properties.

_.values({one: 1, two: 2, three: 3});
=> [1, 2, 3]

So to get your values out of your object, you would just include the Underscore library and use the following code:

var myValues = _.values(MyOBj);
myValues;
// => ["(JSON.stringified object)", "(JSON.stringified object)"]

I highly recommend Underscore, as you will be able to do the same thing for the keys of your Object, as well as perform a bunch of other useful functions.


Option 2: Pure JS Solutions

If you find yourself in the situation where you are including the entire Underscore library just for this one function, you will have a lot of code bloat on your hands. Instead, you may head over to this StackOverflow question where qubyte outlines many solutions. They all pretty much define helpers to accurately perform the function you are looking for, which is why Underscore is just so useful from the outset.

Community
  • 1
  • 1
Bottled Smoke
  • 356
  • 1
  • 6
1

You can do something like this -

var myObj = {
  'obj1': '{ "child1": "child Value 1", "child2": "child Value 2" }',
  'obj2': '{ "child1": "child Value 3", "child2": "child Value 4" }'
}

var keys = Object.keys(myObj);
for (var i = 0; i < keys.length; i++) {
  var str = myObj[keys[i]];
  console.log(JSON.parse(str));
}
Check the console
Aswin Ramakrishnan
  • 3,195
  • 2
  • 41
  • 65