1

Using Array of array to object - javascript and Convert an array to an array of objects as a guide I tried to write a function that results in taking this array of array list:

var list = [['name', 'Sparky'], ['breed', 'lab'], ['age', 4]];

and converting it into this:

{
  name : 'Sparky'
  breed : 'lab',
  age : 4
}

However, when I run the code below:

var list = [
  ['name', 'Sparky'],
  ['breed', 'lab'],
  ['age', 4]
];

function toObjects(data) {
  var keys = data.shift(),
    i = 0,
    k = 0,
    obj = null,
    output = [];

  for (i = 0; i < data.length; i++) {
    obj = {};

    for (k = 0; k < keys.length; k++) {
      obj[keys[k]] = data[i][k];
    }

    output.push(obj);
  }

  return output;
}
var data = [
  ['name', 'Sparky'],
  ['breed', 'lab'],
  ['age', 4]
];

console.log(toObjects(data))

I get this:

console.log(toObjects(data)); //=> 

[ { name: 'breed', Sparky: 'lab' },{ name: 'age', Sparky: 4 } ]

but I need the output to not have an extra array [ ] and to also be listed single file like this:

       {
          name : 'Sparky'
          breed : 'lab',
          age : 4
        }

Any advice? Please and thank you!

Community
  • 1
  • 1

2 Answers2

2

I would use Array.prototype.reduce to perform your transformation as well as argument destructing. Take a look, the code is pretty simple :)

let list = [
  ['name', 'Sparky'],
  ['breed', 'lab'],
  ['age', 4]
];

function toObjects(data) {
  // reduce iterates through every element in the `data` array
  // and accumulates it into the object

  let initialValue = {};
  return data.reduce((obj, [key, value]) => {
    obj[key] = value;
    return obj;
  }, initialValue); // this could be in-lined with `{}`
}

var data = [
  ['name', 'Sparky'],
  ['breed', 'lab'],
  ['age', 4]
];

console.log(toObjects(list))
Rico Kahler
  • 17,616
  • 11
  • 59
  • 85
0

You can use map function to achieve this

var list = [['name', 'Sparky'], ['breed', 'lab'], ['age', 4]];
var newObj = new Object();
list.forEach(function (arr) {
   newObj[arr[0]] = arr[1];
});

console.log(newObj)
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
  • I don't think OP is looking for alternatives. Object of this question is to get output as object and not array. – Rajesh Feb 20 '17 at 06:18
  • Downvote because you are using `Array.map` without returning anything and assigning. This is just wasting `Array.map`. If you just want to process array, use `Array.forEach` – Rajesh Feb 20 '17 at 06:22
  • `newObj[arr[0]] = arr[1];` is used within `map`. – Mairaj Ahmad Feb 20 '17 at 06:23
  • `Array.map` is used to map values based on current values. You are not returning anything inside `.map` so it will return `undefined`. You are not saving output anywhere as well. This is classic case for `.forEach`. A user with your rep should know this – Rajesh Feb 20 '17 at 06:25