Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In order to populate a data-grid that receives array of row objects, I am looking for a good solution to convert an array such as this:

[  
['country', 'population'],
['someplace', 100],
['otherplace', 200]
]

into an array of objects such as this:

[
{country: 'someplace', population: 100},
{country: 'otherplace', population: 200},
]

UPDATE:

this is the solution I am using so far:

 function arrayToRows(arr) {
var defs = [];
var data = [];
var rows = [];
var r;
var obj;



var headerRow = arr.shift(); //remove header row

defs = headerRow.map(function(cell) {
  return {
    field: cell,
    displayName: cell
  }
});


for (var i = 0; i < arr.length; i++) {
  r = arr[i];
  obj = {};

  for (var j = 0; j < defs.length; j++) {
    obj[defs[j].field] = r[j];
  }
  rows.push(obj);
}
return rows;

}

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
834 views
Welcome To Ask or Share your Answers For Others

1 Answer

var array = [  
    ['country', 'population'],
    ['someplace', 100],
    ['otherplace', 200]
];

var keys = array.shift();
var objects = array.map(function(values) {
    return keys.reduce(function(o, k, i) {
        o[k] = values[i];
        return o;
    }, {});
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...