Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

javascript: convert two dimensional array to array of objects using the first 'row' to define properties

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

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

1 Reply

0 votes
by (71.8m points)
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;
    }, {});
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...