如何在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

