2

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"}]';
6
  • What's the desired result ? Commented Feb 8, 2013 at 16:37
  • comma separed Ids like 1234,4321 Commented Feb 8, 2013 at 16:37
  • Naming your initial array "tempString" is a little confusing in my opinion. Commented Feb 8, 2013 at 16:41
  • @SLaks:now it is..:)..@dystroy:its just for question purpose Commented Feb 8, 2013 at 16:43
  • 1
    @Sandy I fixed the JSON in your question, please check this is really what you want to have. Commented Feb 8, 2013 at 16:49

4 Answers 4

3

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(',');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for clean,quick and neat solution.
0

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

Comments

0

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.