I’ve a jQuery.each(data, foo), where data is either a string or a list of strings. I’d like to know if there’s an existing utility function to convert the string to a list, or otherwise perform foo on just the string. So instead of the easy route:
if (!$.isArray(data)) {
foo(0, data); // can't rely on `this` variable
} else {
$.each(data,foo);
}
I was just wondering if there was already a builtin function of jQuery or Javascript that would convert data to a list automatically, like this:
function convert_to_list(data) { return $.isArray(data) ? data : [data]; }
$.each(convert_to_list(data), foo);
Just curious!
Thanks for reading.
Brian
Andy’s approach is a good one. Alternatively, you can always force data to be an array and then feed to jQuery.each
Another option is to always wrap the input in an array regardless of it’s type (string or array), and then flatten it.
flatten, as the name suggests, will flatten multi-level arrays to a single level. So[["foo", "bar"]]becomes["foo", "bar"]. The code them becomes:Various libraries provide the flatten method, and a pure JavaScript implementation can be found here and another example at MDC that only flattens arrays two levels deep.