0

The array is this:

[{name:'name1',id:'id1',val:'001},
 ...
 {name:'name10',id:'id10',val:'010}]

We want to store in the database as a long text string:

name1,id1,001;...;name10,id10,010

values separated by semicolon and comma.

Is there any convenient join or something else to achieve it? (I guess there must be something better than for loop.)

2
  • 1
    If you are happy with Jquery then this one is easy: jsfiddle.net/XWCv8/413 And since the question is not tagged with Jquery I cant add it as answer :( Commented Apr 23, 2015 at 18:54
  • 1
    Since that's not an array, but an object, you cannot use join, and won't get deterministic order unless you are explicit. Commented Apr 23, 2015 at 18:58

3 Answers 3

3
function joinValues(arr, j1, j2) {
  return arr.map(function(o) {
    return Object.keys(o).map(function(k) {
      return o[k];
    }).join(j1)
  }).join(j2);
}

var obj = [{a:1,b:2},{a:'x',b:'y'}];
joinValues(obj, ',', ';'); // => "1,2;x,y"
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! That is certainly beautiful JavaScript. Thanks a lot.
2
array.map(function(o){
  var values = Object.keys(o).map(function(key){
    return o[key];
  });
  return values.join(',');
}).reduce(function(a,b){
  return a + ';' + b;
});

Beware there might be compat issues depending on your platform (map, reduce, Object.keys not available everywhere yet!)

Also, take into account that properties order in regular objects is not guaranteed. With this approach, theoretically you could end up having name1,id1,001;...;id10,name10,010. That might be an issue when mapping the string back to objects.

Comments

1

I'm afraid there isn't a built-in language feature for that, but if you can use ES6, it can look quite elegant

Object.values = obj => Object.keys(obj).map(key => obj[key]);

// so to convert your data
data.map(o => Object.values(o).join(',')).join(';');

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.