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.)

Blaise
  • 18,108
  • 20
  • 89
  • 154
  • 1
    If you are happy with Jquery then this one is easy: http://jsfiddle.net/XWCv8/413/ And since the question is not tagged with Jquery I cant add it as answer :( – Rahul Tripathi Apr 23 '15 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. – Bergi Apr 23 '15 at 18:58

3 Answers3

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"
maerics
  • 133,300
  • 39
  • 246
  • 273
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.

Community
  • 1
  • 1
Matias
  • 4,896
  • 3
  • 28
  • 46
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(';');
Lim H.
  • 9,049
  • 9
  • 43
  • 70