简体   繁体   中英

Converting array of arrays into object?

Trying to convert an array of arrays (where the inner arrays only have two values stored) into an object.

This is what I've got so far:

 function fromListToObject(array) { var obj = {}; for (i in array) { obj[array[i[0]]] = array[i[1]]; }; return obj }; A1=[['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]; console.log(fromListToObject(A1));

But it's giving me an object where the keys are the array pairs, and the values are "undefined."

Halp?

With ES6, you could use

 var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]], object = Object.assign(...array.map(([k, v]) => ({ [k]: v }))); console.log(object); 

Change your code to:

function fromListToObject(array) {
  var obj = {};
  for (i in array) {
      obj[array[i][0]] = array[i][1];
  };
  return obj
};


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

You wrote wrong syntax when get array value.

You can use Array.prototype.reduce() as follows:

 const array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]; const object = array.reduce((result, [key, value]) => { result[key] = value; return result; }, {}); console.log(object); 

Try this:

function fromListToObject(array) {
  return Object.assign.apply({}, array.map(function(subarray) {
      var temp = {}
      temp[subarray[0]] = subarray[1]
      return temp
    })
  )
};


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

It flattens all the arrays into one big object with these key-value pairs:

{ make: 'Ford', model: 'Mustang', year: 1964 }

The Object.fromEntries method does this simply

 var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]; var obj = Object.fromEntries(array); console.log(obj);

More about Object.fromEntries() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM