I have following JavaScript array var arr = ['1', '2', '3', '4' ];
I want to convert this object into a single string such that I it should produce following output: 1 + 2 + 3 + 4
. This is working fine with the help of join
function.
arr.join(' + ')
produces the desired output.
Problem is my simple array is now been converted into a complex object:
var data = [
{
"key": "1",
"IsData": true
},
{
"key": "2",
"IsData": false
},
{
"key": "3",
"IsData": true
},
{
"key": "4",
"IsData": false
}
];
I can loop over this object and produce the desired result 1 + 2 + 3 + 4
.
I want to know if there is a smarter way (WITHOUT LOOPING) to get the desired output. May be by using library like lodash or jquery
Rajaprabhu Aravindasamy :
Try to use Array.prototype.map(),\n\ndata.map(function(val){ return val.key }).join(' + ');\n\n\nDEMO",
2014-07-01T12:19:49
Cᴏʀʏ :
If you're already using jQuery, it too has a map() function:\n\nvar output = $.map(data, function(obj) { return obj.key; }).join(' + ');\n\n\njsFiddle Demo",
2014-07-01T12:27:17
xio4 :
Try this:\n\ndata.reduce(function(pstr, co) {\n return pstr+\" + \"+co.key; \n}, \"\").slice(3);\n",
2014-07-01T12:38:41