如何将数组转换为指定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
- 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.
- Map tags to objects: Use the
map()method to transform each tag string into an object where thenamekey 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
相关产品推荐
相关产品推荐

