如何遍历数组并将属性序列化为字符串
Solution to Consolidate
items into a Single JSON String Got it, let's break down how to solve this problem exactly as you need it. Your goal is to take each items array (which currently holds individual JSON strings) in your dataset, convert those strings into actual objects, then stringify the whole collection back into one JSON string—so later you can just run JSON.parse() on it to get the full array of objects.
Step-by-Step Implementation (JavaScript)
Here's a straightforward way to do this:
// Your original input dataset const originalData = [ { "n":"1", "items": ["{\"id\":\"id1\",\"desc\":\"description1\"}", "{\"id\":\"id2\",\"desc\":\"description2\"}", "{\"id\":\"id3\",\"desc\":\"description3\"}"] }, { "n":"2", "items": ["{\"id\":\"id4\",\"desc\":\"description4\"}"] } ]; // Process each entry to restructure the `items` property const processedData = originalData.map(entry => { // 1. Parse each JSON string in the items array to plain objects const parsedItems = entry.items.map(itemString => JSON.parse(itemString)); // 2. Stringify the entire array of objects into a single JSON string const consolidatedItemsString = JSON.stringify(parsedItems); // 3. Return the updated entry (without mutating the original) return { ...entry, items: consolidatedItemsString }; }); // Check the result console.log(processedData);
What the Output Looks Like
After running the code, processedData will have the structure you need:
[ { "n": "1", "items": "[{\"id\":\"id1\",\"desc\":\"description1\"},{\"id\":\"id2\",\"desc\":\"description2\"},{\"id\":\"id3\",\"desc\":\"description3\"}]" }, { "n": "2", "items": "[{\"id\":\"id4\",\"desc\":\"description4\"}]" } ]
Using the Processed Data Later
When you need to access the actual objects, just parse the items string:
// Example: Get items for the first entry const firstEntryItems = JSON.parse(processedData[0].items); console.log(firstEntryItems); // Logs the array of {id, desc} objects
Key Notes
- Valid JSON Check: Ensure every string in the original
itemsarray is valid JSON. If there's a chance of invalid strings, wrap theJSON.parsecall in atry/catchblock to handle errors without breaking the whole process. - Immutability: Using the spread operator (
...entry) creates a new object instead of modifying the original data, which helps avoid unintended side effects in your code.
内容的提问来源于stack exchange,提问作者ang
相关产品推荐
相关产品推荐

