1

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?

3
  • How about the join method? Commented Dec 4, 2015 at 15:52
  • join on what keys? Commented Dec 4, 2015 at 15:54
  • If your string values are more than just simple digits, you'd want to rely on query formatting methods that are available within the database framework that you are using. Otherwise, you are risking to create invalid strings when they have special symbols in them. Commented Dec 5, 2015 at 9:51

2 Answers 2

6

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());

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

Comments

2

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?'': ',';    
}, '');

Comments

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.