You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将数组转换为带映射键值对的对象?

Convert Array of Field-Value Objects to Key-Value Object in JavaScript

Great question! Turning that array of field-value pairs into a plain object is super straightforward in JavaScript, and we can easily handle the capitalization of the hobbies value as you've shown. Here are a couple of clean approaches:

Using Array.reduce() (Works in all JS environments)

This is a versatile method that lets you build the object incrementally, giving you full control over transforming values as needed:

const inputArray = [
  { field: "firstname", value: "John" },
  { field: "lastname", value: "Doe" },
  { field: "hobbies", value: "singing, basketball" },
];

const result = inputArray.reduce((accumulator, currentItem) => {
  // Adjust the hobbies value to capitalize the first letter
  let itemValue = currentItem.value;
  if (currentItem.field === "hobbies") {
    itemValue = itemValue.charAt(0).toUpperCase() + itemValue.slice(1);
  }
  
  // Add the key-value pair to our accumulator object
  accumulator[currentItem.field] = itemValue;
  return accumulator;
}, {}); // Start with an empty object as the initial accumulator

console.log(result);
// Output: { firstname: "John", lastname: "Doe", hobbies: "Singing, basketball" }

Using Object.fromEntries() (Modern JS, ES2019+)

If you're working with modern browsers or Node.js 12+, Object.fromEntries() is a more concise option. It converts an array of [key, value] pairs directly into an object:

const inputArray = [
  { field: "firstname", value: "John" },
  { field: "lastname", value: "Doe" },
  { field: "hobbies", value: "singing, basketball" },
];

const result = Object.fromEntries(
  inputArray.map(item => {
    let adjustedValue = item.value;
    if (item.field === "hobbies") {
      adjustedValue = adjustedValue.charAt(0).toUpperCase() + adjustedValue.slice(1);
    }
    return [item.field, adjustedValue];
  })
);

console.log(result);
// Same output as above

Bonus: Reusable Capitalization Helper

If you might need to capitalize values elsewhere, extract that logic into a helper function for cleaner code:

const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);

const result = inputArray.reduce((acc, { field, value }) => {
  acc[field] = field === "hobbies" ? capitalizeFirstLetter(value) : value;
  return acc;
}, {});

All these methods will give you exactly the object you're looking for. Pick the one that fits your environment and coding style best!

内容的提问来源于stack exchange,提问作者catandmouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:08:02