0

I am trying to write a function which takes in an array of arrays, and returns an object with each pair of elements in the array as a key-value pair. I have searched stack overflow and came up with the following code. However, my code below only returns the first array { make: 'Ford' }. My code does not return the rest of the arrays. Any suggestions on why my function does not return the rest of the array of arrays?

var array = [
  ['make', 'Ford'],
  ['model', 'Mustang'],
  ['year', 1964]
];

function fromListToObject() {

  for (var i = 0; i < array.length - 1; ++i) {
    var object = {};
    //creates an object as a variable
    var newArray = array[i];
    //creates a variable for the array within the array
    object[i] = newArray[1];
    //sets the object of the element to position 1 of the array within the array
    object[newArray[0]] = object[i];
    //sets the key of the element to position 0 of the array within the array
    delete object[i];
    // removes the previous key of 0
    return object;
  }
}

console.log(fromListToObject(array));

4
  • 2
    Declare object outside of your loop. Commented Mar 23, 2017 at 5:30
  • Try walking through your code with the debugger. Step by step. You might add object as a "watch" to see how its value changes. Commented Mar 23, 2017 at 5:33
  • Possible duplicate of Convert JavaScript array of 2 element arrays into object key value pairs Commented Mar 23, 2017 at 5:34
  • Thank you all for your solutions. I tried to declare the object outside of the loop but it didn't seem to work..The function still only returned the first array of arrays. Commented Mar 23, 2017 at 5:45

3 Answers 3

1

Your code has several issues.

  • The target object is reset to {} in each iteration. So you should move var object = {} out of your loop.

  • You return from inside your loop, which immediately ends it: that should happen after the loop.

  • You iterate one time too few. Remove the - 1:

       for (var i = 0; i < array.length; ++i) {
    
  • There is an assignment to a numerical property, which you delete 2 lines later: that is a costly operation, which you should avoid. Just do the assignment in one operation:

       object[newArray[0]] = newArray[1];
    

Here is everything corrected:

var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];

function fromListToObject() {
  var object = {}; // out of the loop
  for (var i = 0; i < array.length; ++i) { // iterate to last
    var newArray = array[i];
    object[newArray[0]] = newArray[1];
  }
  return object; // out of the loop
}

var obj = fromListToObject(array);

console.log(obj);

ES6 Version

If you can use ES6 syntax, then consider this solution:

function fromListToObject(array) {
    return Object.assign(...array.map( ([key,val]) => ({[key]: val}),{}));
}

const array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];
const obj = fromListToObject(array);
console.log(obj);

Using Map

You might also be interested in the ES6 Map object, which works similarly to an object, and can be constructed from your array in the most simple way:

const mp = new Map(array);

You can then access the key values as follows:

mp.get('make') === 'Ford';

And iterate:

mp.forEach( function (val, key) {
    console.log(key, val);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks trincot. I was curious to understand why my code didn't work but your code works as well!!
I added a list of issues in your code and a version of it that has it corrected.
1

Try this

You have declared obj inside the loop. During iteration

object = Object {make: "Ford"}, i = 0

After the first iteration your function

console.log(fromListToObject(array));

is called. This is because you call the return inside the loop, this should be done outside the loop. Rewrite your code as

var array = [
    ['make', 'Ford'],
    ['model', 'Mustang'],
    ['year', 1964]
  ],
  i, j = array.length,
  object = {}

function fromListToObject() {

  for (i = 0; i < j; i++) {
    var newArray = array[i];
    object[i] = newArray[1];
    object[newArray[0]] = object[i];
    delete object[i];
  }
  return object;
}

console.log(fromListToObject(array));

var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];

var obj = {};
array.forEach(function(data){
    obj[data[0]] = data[1]
});
console.log(obj);

4 Comments

That works just fine, but what is wrong with the OP's code?
In OP's code, the result obtained is just { "make": "Ford" }
torazaburo mean, you should explain why OP's code was failing and why your code gives proper output. Remember, you are answering for readers and not just OP.
Thanks Geethu! I was curious to understand why my code didn't work but your code works as well!!
0

While: Not Counting!

object = {};
while( array[0] )object[ array[0][0] ] = array[0][1], array.shift();

will result in:

object;
>> Object { make: "Ford", model: "Mustang", year: 1964 }

array;
>> Array [ ]

This action will actually dispatch array members for patching the object! The array content will be physically dislocated to the newly declared object.

Comments

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.