Reputation: 2831
I have an array
of objects structured like this:
[{ a: '1', b : '2'}, {a : '3', b : '4'}]
For the purpose of preparing data for insertion into database, I need a string of object values like this:
('1', '2'),('3', '4')
With the same ordering of values.. apart from the naive way of iterating through each object in array and constructing a string, is there a better much easier way of doing this?
Upvotes: 1
Views: 65
Reputation: 613
For on line lovers.
var arr = [{ a: '1', b : '2'}, {a : '3', b : '4'}];
var result = arr.reduce(function(result, item, i){
return result + "('" + item.a + "', '" + item.b + "')" + i===arr.length-1?'': ',';
}, '');
Upvotes: 2
Reputation: 28445
Try following
var arr = [{ a: '1', b : '2'}, {a : '3', b : '4'}];
var result = arr.map(function(item){
return "('" + item.a + "', '" + item.b + "')";
});
console.log(result);
console.log(result.join());
Upvotes: 6