简体   繁体   English

将数组数组转换为对象?

[英]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 使用ES6,您可以使用

 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: 您可以按如下方式使用Array.prototype.reduce()

 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 Object.fromEntries方法可以简单地做到这一点

 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更多关于Object.fromEntries() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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