求助:将字符串数组转换为JavaScript对象的方法
Solution to Convert Semi-Structured String Array to Object Array
Got it, let's work through this problem! Your input strings are semi-structured key-value lists separated by commas, but they aren't valid JSON—so JSON.parse() can't process them directly. Here's a straightforward, customizable approach to turn them into the object array you need:
Step-by-Step Explanation
- Split each string into individual key-value pairs: Use
split(',')to break the string apart at each comma. - Extract keys and values: For each pair, split at the first colon (
:) to separate the key (left side) from the value (right side). - Clean up values: Handle ellipsis (
…) by removing them, and decide how to treat empty values (e.g., set tonullor leave as an empty string). - Map over the input array: Apply the parsing function to every string in your input array to get the final object array.
Example Code (JavaScript)
const inputStrings = [ "Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:", "Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:" ]; function parseSemiStructuredString(str) { const keyValuePairs = str.split(','); const parsedObject = {}; keyValuePairs.forEach(pair => { const colonPosition = pair.indexOf(':'); if (colonPosition === -1) return; // Skip any invalid pairs without a colon const key = pair.slice(0, colonPosition).trim(); let value = pair.slice(colonPosition + 1).trim(); // Remove ellipsis characters (adjust if you want to keep them instead) value = value.replace(/…/g, ''); // Handle empty values: set to null or leave as empty string parsedObject[key] = value === '' ? null : value; }); return parsedObject; } // Convert the input array to the desired object array const resultArray = inputStrings.map(parseSemiStructuredString); console.log(resultArray);
Output
Running this code will give you:
[ { "Time": "25/10/2019 14:49:47.41", "Server": "Daniel.Europe.Aitical", "Area": "Europe", "Site": null, "Station": "Aberdeen", "Stream": null }, { "Time": "25/10/2019 14:49:48.16", "Server": "Daniel.Europe.U", "Area": "Europe", "Site": "United Kingdom", "Station": null, "Stream": null } ]
Customization Tips
- If you need to keep ellipsis instead of removing them, delete the
value.replace(/…/g, '')line. - If empty values should stay as empty strings instead of
null, changeparsedObject[key] = value === '' ? null : value;toparsedObject[key] = value;. - If your strings ever have commas inside values (e.g.,
Description:Hello, world), you'll need a more robust parser (like using a regex that ignores commas inside quotes), but this solution works perfectly for your provided input.
内容的提问来源于stack exchange,提问作者Abhinav
相关产品推荐
相关产品推荐

