Reputation: 14216
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!
Upvotes: 1
Views: 539
Reputation: 356
If you use Underscore, you can simply use the Values helper to return an array of all the values in your object.
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.
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.
Upvotes: 2
Reputation: 3213
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
Upvotes: 1