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

如何拆分指定JSON对象:按键名末尾数字生成独立子对象

Solution to Split JSON Object by Suffix Numbers

Step-by-Step Explanation

Got it, let's break down how to turn your flat JSON object into an array of clean sub-objects grouped by the numeric suffixes in the keys. The core idea is to group key-value pairs by their trailing number, then strip that number from the keys to create tidy sub-objects.

Code Implementation

Here's a straightforward JavaScript solution tailored to your input:

const myjson = { 
  "productname0": "Test1", 
  "price0": "10", 
  "categories0": "61", 
  "type0": "Physical", 
  "availability0": "available", 
  "weight0": "0.5", 
  "productname1": "Test2", 
  "price1": "20", 
  "categories1": "61", 
  "type1": "Physical", 
  "availability1": "available", 
  "weight1": "0.7" 
};

// Initialize a grouping object to hold sub-objects by their suffix number
const groupedProducts = {};

// Loop through each key-value pair in the original object
for (const [fullKey, value] of Object.entries(myjson)) {
  // Use regex to split the key into its base name and numeric suffix
  const keyMatch = fullKey.match(/^(\D+)(\d+)$/);
  
  if (keyMatch) {
    const [_, baseKey, suffix] = keyMatch;
    // Create a new sub-object for the suffix if it doesn't exist yet
    if (!groupedProducts[suffix]) {
      groupedProducts[suffix] = {};
    }
    // Add the cleaned key-value pair to the correct sub-object
    groupedProducts[suffix][baseKey] = value;
  }
}

// Convert the grouped object into the final array of sub-objects
const finalResult = Object.values(groupedProducts);

console.log(finalResult);

How This Works

  • Grouping Logic: The groupedProducts object acts as a temporary container, where each key is a numeric suffix (0, 1) and the value is the sub-object for that product.
  • Key Cleaning: The regex /^(\D+)(\d+)$/ pulls out the base key (like productname from productname0) and the trailing number, so we can rename keys without the suffix.
  • Final Array: Object.values(groupedProducts) extracts all the sub-objects from the grouping container and turns them into a neatly ordered array.

Expected Output

Running this code will produce exactly the structure you need:

[
  {
    productname: "Test1",
    price: "10",
    categories: "61",
    type: "Physical",
    availability: "available",
    weight: "0.5"
  },
  {
    productname: "Test2",
    price: "20",
    categories: "61",
    type: "Physical",
    availability: "available",
    weight: "0.7"
  }
]

Bonus: This solution is scalable — if you add more products with suffixes like 2, 3, etc., it will automatically group them into additional sub-objects in the array without any code changes.

内容的提问来源于stack exchange,提问作者Ankit Parmar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:04:51