最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON manipulation in Node.js - Stack Overflow

programmeradmin5浏览0评论

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?

Share Improve this question edited Dec 5, 2015 at 3:24 Kijewski 26.1k14 gold badges107 silver badges147 bronze badges asked Aug 26, 2015 at 12:09 SniperSniper 2,45211 gold badges45 silver badges50 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 6

Try 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/

发布评论

评论列表(0)

  1. 暂无评论