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

如何基于含逗号分隔多值的多属性高效生成对象数组?

Solution: Split Object into Array Based on Comma-Separated Properties

Here's a clean, concise way to handle this task—using array mapping and object spreading to keep the code readable and minimal:

const obj = {
  id: 1,
  date: "2021",
  tst1: "111, 222",
  tst2: "AAA, BBB"
};

// Split comma-separated values into trimmed arrays (removes extra spaces)
const tst1Values = obj.tst1.split(',').map(str => str.trim());
const tst2Values = obj.tst2.split(',').map(str => str.trim());

// Generate the result array by pairing values from both arrays
const result = tst1Values.map((val1, index) => ({
  ...obj, // Copy all original properties
  tst1: val1, // Override tst1 with current value
  tst2: tst2Values[index] // Match with corresponding tst2 value
}));

console.log(result);

How This Works:

  1. Split & Clean: We first split the comma-separated strings for tst1 and tst2 into arrays, using trim() to eliminate any extra whitespace around values (since your example includes spaces after commas).
  2. Map to New Objects: Using map() on one of the split arrays (since you confirmed their lengths are always equal), we create a new object for each index. We spread the original object to retain all other properties, then override tst1 and tst2 with the paired values from their respective arrays.

Bonus: Generalize for Multiple Properties

If you ever need to handle more than two comma-separated properties, here's a reusable function to scale the solution:

function splitObjectByProps(originalObj, propNames) {
  // Split all target properties into trimmed arrays
  const propArrays = propNames.map(prop => 
    originalObj[prop].split(',').map(str => str.trim())
  );
  
  // Create new objects by pairing values across all arrays
  return Array.from({ length: propArrays[0].length }, (_, index) => {
    const newObj = { ...originalObj };
    propNames.forEach((prop, propIndex) => {
      newObj[prop] = propArrays[propIndex][index];
    });
    return newObj;
  });
}

// Usage example:
const result = splitObjectByProps(obj, ['tst1', 'tst2']);

This function takes the original object and an array of property names to split, making it flexible for future use cases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:06:49