可以使用 JavaScript 中的 reduce() 方法将数组转换为对象。

例如,将以下数组:

const arr = [
  ['name', 'John'],
  ['age', 30],
  ['city', 'New York']
];

转换为以下对象:

const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

可以使用以下代码实现:

const arr = [
  ['name', 'John'],
  ['age', 30],
  ['city', 'New York']
];

const obj = arr.reduce((acc, [key, value]) => {
  acc[key] = value;
  return acc;
}, {});

console.log(obj);

输出结果:

{
  name: 'John',
  age: 30,
  city: 'New York'
}
JavaScript 数组转换为对象:使用 reduce() 方法

原文地址: https://www.cveoy.top/t/topic/mU5Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录