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

JavaScript中实现对象集合的ref命名属性递增添加方案

Solution to Dynamically Increment Ref Property Names

Here's a straightforward way to achieve what you're looking for—we'll extract existing ref keys, find the highest number, increment it, and assign your test object to the new property:

var obj = { ref01:{ test:"abc" }, ref02:{ test:"xyz" }, ref03:{ test:"pqr" } };
const test = { test:"def" };

// Step 1: Get all property keys in obj that start with "ref"
const refKeys = Object.keys(obj).filter(key => key.startsWith('ref'));

// Step 2: Extract the numeric part from each ref key and find the maximum value
const maxRefNumber = Math.max(...refKeys.map(key => parseInt(key.slice(3), 10)));

// Step 3: Generate the new property name with padded leading zero (to match existing 2-digit format)
const newRefKey = `ref${String(maxRefNumber + 1).padStart(2, '0')}`;

// Step 4: Assign the test object to the new property
obj[newRefKey] = test;

console.log(obj);
// Output: { ref01: { test: 'abc' }, ref02: { test: 'xyz' }, ref03: { test: 'pqr' }, ref04: { test: 'def' } }

Breakdown of Each Step:

  • Extracting Ref Keys: We use Object.keys(obj) to get all property names, then filter for those starting with "ref" to ignore any unrelated properties.
  • Finding the Highest Number: For each ref key, we slice off the "ref" prefix, convert the remaining string to an integer, then use Math.max() to find the largest number. The spread operator (...) converts the array of numbers into individual arguments for Math.max().
  • Generating the New Key: We increment the max number by 1, then use padStart(2, '0') to ensure it's always two digits (so 4 becomes "04", keeping consistency with your existing naming). We template this into the new key name.
  • Assigning the Object: Using bracket notation (obj[newRefKey]), we dynamically assign the test object to the new property—this works because bracket notation lets us use variables as property names, unlike dot notation.

Edge Case Handling (Optional):

If there's a chance your obj might not have any existing "ref" properties, you can add a fallback to start with ref01:

const maxRefNumber = refKeys.length > 0 
  ? Math.max(...refKeys.map(key => parseInt(key.slice(3), 10))) 
  : 0;

内容的提问来源于stack exchange,提问作者007DevilsWorkshop

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:32:38