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

如何遍历数组并将属性序列化为字符串

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 items array is valid JSON. If there's a chance of invalid strings, wrap the JSON.parse call in a try/catch block 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:32:14