0

I want to iterate a JSON Object and then join/ merge each result into string.

Here is my codes:

JSON:

var jsonObj = [ {"tag": "article"}, {"tag": "header"} ]

jQUery:

var json = $.parseJSON(jsonObj);
var element = $.each(json, function(i, val){
    var finder = 'find("' + val.tag + '")';         
    return finder;
});
alert(element);

I tried using .join() after $.each(), like this $.each(...).join(); but it is returning object.

I also using .get(), like this $.each(...).get().join(); but returning error.

What can I use to join the result returned in each iteration and then merge them and output as a string?

2
  • what is 'find()' as a string used for? Are you wanting to invoke as function? Commented May 3, 2015 at 18:02
  • I want to write it as executable js string. Commented May 3, 2015 at 18:08

1 Answer 1

2

Fiddle

Use .map() chained with .join() to get the values in a string.

var jsonObj = [{"tag": "article"}, {"tag": "header"}]
var json = $.parseJSON(jsonObj);
var element = $.map(json, function(obj){
    var finder = 'find("' + obj.tag + '")';         
    return finder;
}).join(' , ');
console.log(element)

Note that .each() does not support .get().

Sign up to request clarification or add additional context in comments.

3 Comments

it works... but I can't then use index and in inside the iteration... like so: var element = $.map(json, function(i, obj){ var finder = ""; if(json.length - i == json.length) { finder += i + " "; } if("tag" in obj) { finder += '$("' + obj.tag + '")'; } return finder; }).join(' , ');
Yes you can, the syntax is a little different for .map() with index. Check this jsfiddle.net/jdgr9dyz/1 . Instead of function(i, obj) its function(obj,i)
You beat it once again...!

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.