如何基于含逗号分隔多值的多属性高效生成对象数组?
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:
- Split & Clean: We first split the comma-separated strings for
tst1andtst2into arrays, usingtrim()to eliminate any extra whitespace around values (since your example includes spaces after commas). - 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 overridetst1andtst2with 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
相关产品推荐
相关产品推荐

