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

如何将数组转换为指定JSON格式?示例需求技术求助

How to Convert an Array to the Target JSON Format

Hey there! Let's walk through how to turn your original array into the desired format. First, let's clarify your starting point: you have an array with a single string containing comma-separated tags, and you want to convert each tag into an object with a name property.

Step-by-Step Solution

  1. Split the comma-separated string: Pull the string from your initial array, then split it into individual tag strings using the comma (and any surrounding whitespace) as the separator.
  2. Map tags to objects: Use the map() method to transform each tag string into an object where the name key is set to the tag value.

Basic Code Example

var arr = ["tag1, tag2"];
// Extract and split the tag string into an array of individual tags
const individualTags = arr[0].split(', ');
// Convert each tag to the desired object format
const formattedArr = individualTags.map(tag => ({ name: tag }));

console.log(formattedArr);
// Output: [ {"name": "tag1"}, {"name": "tag2"} ]

Handling Edge Cases

If your initial array might have multiple comma-separated strings (e.g., ["tag1, tag2", "tag3, tag4"]), or if tags have inconsistent spacing around commas, use these tweaks:

  • For multiple string elements: Use flatMap() to split each string and flatten the results into a single array of objects:
    var arr = ["tag1, tag2", "tag3, tag4"];
    const formattedArr = arr.flatMap(str => 
      str.split(/,\s*/).map(tag => ({ name: tag }))
    );
    
    console.log(formattedArr);
    // Output: [ {"name": "tag1"}, {"name": "tag2"}, {"name": "tag3"}, {"name": "tag4"} ]
    
  • For inconsistent spacing: The regex /,\\s*/ splits on commas followed by any number of whitespace characters, so it works even if tags are formatted like "tag1,tag2" or "tag1 , tag2".

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:11:28