I have a JSON string: [ { name: 'Bob' }, { name: 'Kim' }, { name: 'Jack' } ]
and I want to save all list of names in an array. Is there any proper way to do that rather than looping?
I have a JSON string: [ { name: 'Bob' }, { name: 'Kim' }, { name: 'Jack' } ]
and I want to save all list of names in an array. Is there any proper way to do that rather than looping?
- You can get information out of the string with a RegEx – Vsevolod Goloviznin Commented Aug 26, 2015 at 12:11
- 3 This is not valid JSON. Please don't call just any JavaScript object JSON ... – Kijewski Commented Aug 26, 2015 at 12:43
2 Answers
Reset to default 6Try using Array.prototype.map()
:
[{name: 'Bob'}, {name: 'Kim'}, {name: 'Jack'}].map(function(x) {return x.name});
If it's a string, you need to call JSON.parse()
before, like that:
var json = JSON.parse('[{"name": "Bob"}, {"name": "Kim"}, {"name": "Jack"}]');
var names = json.map(function(x) {return x.name});
Note that you have to use double quotes instead of apostrophes to make it a valid JSON string.
Your string should look like this:
var str = '[{ "name": "Bob" }, { "name": "Kim" }, { "name": "Jack" } ]';
Then you can use:
var jsonObj = JSON.parse(str);
To extract the names use the function from Gothdo:
var names = jsonObj.map(function(x) {return x.name});
Here is the fiddle: https://jsfiddle/qjn46u4z/4/