-2

I am being passed a key/value object called obj that needs to convert to a list of arrays in an array ( arr[ [key: value] [key: value] ] )

function convertObjectToList(obj) {
  var arr = [];
  var i = 0;
  for(var key in obj){
    arr[0][i][0] = key;
    arr[0][i][1] = obj[key];
    i++;
  }
  return arr;
}
Nick
  • 463
  • 4
  • 13
  • You can't have `key:value` in an array. What are you really trying to get as the result? Show a sample input and (valid) output. – Barmar Jun 27 '17 at 21:03
  • What is the problem? What is your target? – Chandan Purbia Jun 27 '17 at 21:03
  • It looks like you will be receiving undefined errors in that loop as `arr[0]` is `undefined` (and so are each children `arr[0][i]` `arr[0][i][0]`) you would need to define them before you try to set their properties – Patrick Barr Jun 27 '17 at 21:04
  • 1
    ... `Object.entries(obj)` –  Jun 27 '17 at 21:21

2 Answers2

0

You could use Array#map with Object.keys and return a new object for each property.

function convertObjectToList(object) {
    return Object.keys(object).map(function (k) {
        var temp = {};
        temp[k] = object[k];
        return temp;
    });
}

ES6

function convertObjectToList(object) {
    return Object.keys(object).map(k => ({ [k]: object[k] }));
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

You can't assign to indexes of an array element until you create the array element. Since there's no arr[0], you can't assign to arr[0][i]. The solution is to iniialize the array with an inner array already in it.

For the third level, you can just use an array literal, you don't need to assign to indexes. And you can use .push() to add elements to an array, rather than incrementing i.

function convertObjectToList(obj) {
  var arr = [[]];
  for(var key in obj){
    arr[0].push([key, obj[key]]);
  }
  return arr;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612