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

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 each id, turns it uppercase, then appends the rest of the string. This gives us "Source" from "source" and "Destination" from "destination".
  • Computed Property Names: Wrapping capitalizedKey in 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() to journeyDetails—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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:53:18