I have an array of objects and some of the objects have a property that has commas in it. What I want to do is if that object has a property that has commas in it, I want to split that into a new object and recursively copy all the other properties into a new array element.
Example: I need to convert this array of objects:
[ {
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' },
]
to this:
[ {
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' },
]
By splitting at prop1, then recursively copying all the other properties into the new array element.
edit: I was able to figure it out actually in google sheets but couldn't quite port this over to vanilla JS:
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, '');
}