5

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;

}

2
  • 1
    have you tried anything ? Commented Apr 7, 2014 at 16:01
  • yes, I have solved it, but interested in better solutions. will update answer with my solution.... Commented Apr 7, 2014 at 16:02

8 Answers 8

21
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;
    }, {});
});
Sign up to request clarification or add additional context in comments.

Comments

4

let array = [['country', 'population'],['someplace', 100],['otherplace', 200]];
let [keys, ...rows] = array;
let result = rows.map(r => (keys.reduce((o, k, i) => (o[k] = r[i], o), {})));
console.log(result)

Comments

3

Hey by using the library underscore.js (http://underscorejs.org/#object) you can accomplish this really easily like this:

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

for(var index=1; index<array.length; index++){
    output.push(_.object(array[0],array[index]));
}

console.log(output);

Checking this link: http://jsfiddle.net/BqA3Y/2/

Comments

2

Using a combination of map and forEach you can map the subsequent array elements to the columns specified in the first element.

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

var cols = arr.shift();
newArr = arr.map(function(element,index){
   var newObj = {};
   element.forEach(function(data,index){
      newObj[cols[index]]=data;
   });
   return newObj;
});

Comments

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

var objects = [], one = array[0][0], two = array[0][1];

for (var i = 1, len = array.length; i < len; i++) {
    var object = {};
    object[one] = array[i][0];
    object[two] = array[i][1];
    objects.push(object);
}

console.log(objects);

DEMO

4 Comments

This isn't exactly an answer to what was asked, if I understand the question correctly. The first row is supposed to be dynamic (not always country/population) so this would not fulfill the needs of the OP.
@Brett I thought it was just for demonstration. Nevermind, editing.
The length of the keys array is probably dynamic as well…
@Bergi Yep, I should have further modified my code, you are right, but I had gone to sleep. Nevertheless, your answer's much better !
1

You would need to use a bit of iteration to do this! The following code is an untested example to demonstrate what you would have to do.

function convertToObjectArray(table)
{
    var output = [];

    for(var i = 1; i < table.length; i++)
    {
        var obj = {};
        for(var x = 0; x < table[0].length; x++)
         obj[table[0][x]] = table[i][x];

         output.push(obj);
    }

    return output;
}

Another note with this example is you should edit this, however, to make sure the subsequent arrays are the same length or you could run into null values.

Comments

1

You can do this pretty nicely with destructuring and Object.fromEntries():

const arr = [ ['country', 'population'], ['someplace', 100], ['otherplace', 200] ];
const [props, ...valsArr] = arr;
const res = valsArr.map(vals => Object.fromEntries(vals.map((val, i) => [props[i], val])));
console.log(res);

Explanation:

const [props, ...valsArr] = arr

This creates two new variables, props being the first value in your array:

['country', 'population']

and valsArr as being the remaining elements in your array:

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

Next, we use .map() on this array to map each inner [place, population] array to an array of objects. To do this, we use Object.fromEntries() on a mapped version of each [place, population] array. The mapped version of each inner array turns into:

[
  ["country", place],  // props[i] would be 'country' from the above `props` array
  ["population", population] // props[i+1] would be 'population' from the above `props` array
]

The above array of [prop, value] inner arrays can be passed to Object.fromEntries(), which will be an object for you with the keys from the first index and the values from the second index.

Comments

-1
function toObjects (array) {
  var new_array = [];
  var headers = [];

  for(var i = 0; i < array.length; i++){
    var obj = {};
    for(var j = 0; j < array[i].length; j++){
      if(i === 0){
        headers.push(array[i][j]);
      } else {
        obj[headers[j]] = array[i][j];
      }
    }
    if(i > 0){
      new_array.push(obj);
    }
  }
  return new_array;
}

1 Comment

['country', 'population'] is supposed to be dynamic

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.