Reputation: 1155
I want to fetch comma separated IDs and types from below string.
I tried through split but that requires multiple split to fetch desired result.
Please suggest an efficient way to fetch desired output like like 1234,4321
using js/jquery.
var tempString=
'[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"},
{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
Upvotes: 2
Views: 839
Reputation: 2693
first off what you have above isn't a string, it is an array of objects.
BUT
if it were a string (like so )
var tempString = '[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"}]
[{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
Then you would want to use something like .match(); https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match
var IDs = tempString.match(/([0-9]+)/gi);
Upvotes: 0
Reputation: 382150
To get "1234,4321"
, you can do
var ids = tempString.map(function(v){return v.id}).join(',');
If you want to be compatible with IE8, then you can do
var ids = $.map(tempString, function(v){return v.id}).join(',');
Following question edit :
If tempString
isn't an array but really a JSON string, then you'd do
var ids = $.map(JSON.parse(tempString), function(v){return v.id}).join(',');
Upvotes: 3
Reputation: 548
You should use any Javascript parser api for JSON to decode the given string into keys and subsequent values. As mentioned by 'Miquel', jQuery has one
Upvotes: 0
Reputation: 15675
As pointed out, that's not a String in your example. Some quotation marks went missing.
At any rate, look into @dystroy's answer, but I think you are dealing with JSON objects, and you should probably be useing a json parser (or even javascripts raw eval if you must) and then fetch your components as object properties and arrays.
Check out jquery's parseJSON
Upvotes: 0