JavaScript实现将数组元素转为首字母大写对象键并添加至数组的需求
Hey there! Let's adjust your code to generate that array with dynamically capitalized keys you need. Here's the solution:
Step-by-Step Fix
First, we'll modify how you create each object in the map loop—using computed property names and a quick string transformation to capitalize the key.
Modified Code
this.journeyIds = ["source", "destination"]; this.journeyDetails = this.journeyIds.map((id) => { // Convert the id to a capitalized key (e.g., "source" → "Source") const capitalizedKey = id.charAt(0).toUpperCase() + id.slice(1); // Use computed property syntax to set the dynamic key return { [capitalizedKey]: this.el("#" + id).inputValue }; });
What Changed?
- Capitalizing the Key: The line
id.charAt(0).toUpperCase() + id.slice(1)takes the first character of eachid, turns it uppercase, then appends the rest of the string. This gives us "Source" from "source" and "Destination" from "destination". - Computed Property Names: Wrapping
capitalizedKeyin square brackets[]tells JavaScript to use the value of that variable as the object's property name, instead of treating it as a literal string. That's how we get dynamic keys instead of the fixed "id". - Cleaner Array Creation: Instead of initializing an empty array and pushing items to it, we directly assign the result of
map()tojourneyDetails—this is a more concise, idiomatic way to transform arrays in JS.
Example Output
If your input values are "LMP" for the source field and "LKO" for the destination field, journeyDetails will end up as:
[{ Source: "LMP" }, { Destination: "LKO" }]
内容的提问来源于stack exchange,提问作者nayan verma
相关产品推荐
相关产品推荐

