JSFiddle - React, Tailwind, and code Playground
by hamix
JavaScript
//merge variants returns {["21 inch", "27 inch"], type: "Screen Size"}
var mergeVariants = function(s) {
//if the type is the same as one already in an object, get that object and add the name to the names array
var variant = {type: "", names: []};
var variants = [];
for(var i = 0; i < s.types.length; i++) {
if(variant.type === "")
{
variant.type = s.types[i];
variant.names[i] = s.names[i];
} else if(variant.type === s.types[i]){
variant.names[i-1] = s.names[i];
}
}
return variant;
}
//mapVariant returns {["21 inch","Silver","27 inch"], ["Screen Size","Colour"," Screen Size"]}
var mapVariant = function(s) {
var re = /\[([\s\S]+?)\]{([\s\S]+?)}\[\/\1\]/g;
var variants = [];
var valueObj = {types: [], names: []};
var x;
while ((x = re.exec(s)) !== null) {
var type = x[1];
var name = x[2];
valueObj.types.push(type);
valueObj.names.push(name);
}
return valueObj;
}
var s = [{Name: '[Screen Size]{27 inch}[/Screen Size][Colour]{Silver}[/Colour][Screen Size]{21 inch}[/Screen Size]'}];
var mp=mapVariant(s);
alert(JSON.stringify(mp));
var res=mergeVariants(mp);
alert(JSON.stringify(res));