I\'m trying to iterate over a \"value\" list and convert it into a string. Here is the code:
var blkstr = $.each(value, function(idx2,val2) {
Converting From Array to String is So Easy !
var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""
That's it Now A is a string. :)
Shouldn't confuse Array's with Lists... This is a list: {...} and has no length, or other Array properties.
This is an Array: [...] and you can use array functions, methods and so, like someone suggested here: someArray.toString();
"someObj.toString();" just will not work on any other objects type, like Lists. ;-)
this's my function, convert object or array to json
function obj2json(_data){
str = '{ ';
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += "'" + i + "':" + obj2arr(v) ;
else if ($.type(v)== 'array')
str += "'" + i + "':" + obj2arr(v) ;
else{
str += "'" + i + "':'" + v + "'";
}
});
return str+= '}';
}
i just edit to v0.2 ^.^
function obj2json(_data){
str = (($.type(_data)== 'array')?'[ ': '{ ');
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += '"' + i + '":' + obj2json(v) ;
else if ($.type(v)== 'array')
str += '"' + i + '":' + obj2json(v) ;
else{
if($.type(_data)== 'array')
str += '"' + v + '"';
else
str += '"' + i + '":"' + v + '"';
}
});
return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
var arr = new Array();
var blkstr = $.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
return arr;
}).join(', ');
console.log(blkstr);
OR
var arr = new Array();
$.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
});
console.log(arr.join(', '));
If value
is associative array, such code will work fine:
var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
(output will appear in the dev console)
As Felix mentioned, each()
is just iterating the array, nothing more.
Here's an example using underscore functions.
var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");
Final output would be "moe,larry,curly"