如何修改数组并转换为JSON?ES6实现结果异常排查
Hey there, let's sort out this JSON formatting problem you're facing. First, let's break down what's wrong with your current result:
{"Quotes:true","Flight Logs:true","Currency Records:true","FTD:true","Maintenance Tracker:true"}
This isn't valid JSON because:
- Object keys must be wrapped in double quotes (e.g.,
"Quotes"instead ofQuotes) - The key-value pairs are formatted as strings separated by commas, instead of proper
key: valueentries inside the object.
Correct ES6 Implementation
Assuming your original array looks like this (a list of the keys you want):
const originalArray = ["Quotes", "Flight Logs", "Currency Records", "FTD", "Maintenance Tracker"];
Here are two clean ES6 ways to convert it to valid JSON:
Method 1: Use Object.fromEntries()
This is the most concise approach for modern JavaScript environments:
// Convert array to an object where each key maps to true const resultObj = Object.fromEntries(originalArray.map(item => [item, true])); // Convert the object to valid JSON const validJSON = JSON.stringify(resultObj, null, 2); console.log(validJSON);
Method 2: Use Array.reduce()
If you need more control (or support slightly older environments), reduce works great too:
const resultObj = originalArray.reduce((acc, item) => { acc[item] = true; return acc; }, {}); const validJSON = JSON.stringify(resultObj, null, 2); console.log(validJSON);
What You'll Get
Both methods will output this valid, properly formatted JSON:
{ "Quotes": true, "Flight Logs": true, "Currency Records": true, "FTD": true, "Maintenance Tracker": true }
Why Your Original Approach Failed
It looks like you might have tried manually concatenating strings to build the JSON, which is error-prone. Always use JSON.stringify() on a properly structured JavaScript object—this ensures the output follows JSON syntax rules automatically.
内容的提问来源于stack exchange,提问作者Lee

