将数组转换为对象的最佳方法

Best way to convert array to object

最好的转换方法是什么

const items = [
  { name: "Leon", url: "../poeple" },
  { name: "Bmw", url: "../car" }
];

使用 javascript :

const result = {
  Leon: "../poeple",
  Bmw: "../car"
};

您可以将对象映射为条目并从中获取对象。

const
    items = [{ name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" }],
    result = Object.fromEntries(items.map(({ name, url }) => [name, url]));

console.log(result);

另一种方式(在您的示例中测试):

function convertit (src) {
  var dest = {}, i;
  for (i = 0; i < src.length; i++) {
    var record = src[i];
    dest[record.name] = record.url;
  }
  return dest;
}

你可以减少数组:

const items = [{
    name: "Leon",
    url: "../people"
  },
  {
    name: "Bmw",
    url: "../car"
  }
];

const o = items.reduce((o, el) => {
  o[el.name] = el.url;
  return o;
}, {});

console.log(o)

Array.prototype.reduce 方法非常灵活,可用于将数组缩减为另一个实体:

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

如您所见,有许多不同的方法。但是,如果您是 JavaScript 的新手,也许在新对象中创建新键和值的简单 loop over the array 会更容易理解。

const items=[{name:"Leon",url:"../poeple"},{name:"Bmw",url:"../car"}];

const out = {};

for (const obj of items) {
  out[obj.name] = obj.url;
}

console.log(out);

这样试试

const items = [
   { name: "Leon", url: "../poeple" },
   { name: "Bmw", url: "../car" }
];

const newObj = Object.fromEntries(items.map(ele => [ele.name,ele.url]));
console.log(newObj);

或者您可以像这样创建函数

const items = [
    { name: "Leon", url: "../poeple" },
    { name: "Bmw", url: "../car" }
  ];


const convertArrayToObject = (array, key) => {
const initialValue = {};
   return array.reduce((obj, item) => {
    return {
      ...obj,
      [item[key]]: item.url,
    };
  }, initialValue);
};

console.log(convertArrayToObject(items, "name"));