I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements.
For example, consider this original array:
[ {
prop1: ' text1 , text2 , text3 ',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: ' text1 , text2 , text3 ',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
]
We need to transform it into the following structure:
[ {
prop1: 'text1',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: 'text2',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: 'text3 ',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: 'text1',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
{
prop1: 'text2',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
{
prop1: 'text3',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
]
The idea is to split at prop1 and then recursively copy all other properties into the new array element.
Additionally, I managed to solve a similar problem in Google Sheets but had difficulty translating it to vanilla JavaScript:
function splitColumnAndRepeatRows(anArray, splitColumnIndex) {
var output = [];
for (i in anArray){
var splitArray = anArray[i][splitColumnIndex].split(",");
for (j in splitArray){
var row = anArray[i].slice(0);
row[splitColumnIndex] = alltrim(splitArray[j]);
output.push(row);
}
}
return output;
}
function alltrim(str) {
return str.replace(/^\s+|\s+$/g, '');
}