Js array operation

var str = "abc-a,add-a,ccc-b,ccc-d,abc-a,abc-b,abc-f,tbg-g";
convert the above string to the following array form:

var arr = [
    {"name" : "abc", "nameIdx":[{"site" : "a"}]},
    {"name" : "add", "nameIdx":[{"site" : "a"}]},
    {"name" : "ccc", "nameIdx":[{"site" : "b"},{"site" : "d"}]},
    {"name" : "abc", "nameIdx":[{"site" : "a"},{"site" : "b"},{"site" : "f"}]},
    {"name" : "tbg", "nameIdx":[{"site" : "g"}]}
]
The

string format is concatenated with commas in the form of abc-y. Unlimited number, the value of abc3 can be 26 arbitrary lowercase letters, can be the same. The value of y is 26 lowercase letters and can only be one. "name", "nameIdx" and "site" are field names in the converted array.

Mar.14,2021

you can record the last name to observe the changes and then add new items to the results. The idea is for reference

.

<br>

function fn(str){
    var tmpObj={};
    var newArr=[];
    var arr = str.split(",");
    arr.map(function(item){  //arrtmpObj
       var itemA=item.split("-");
       var key=itemA[0];
       var v=itemA[1];
       if(tmpObj[key]){ //
           tmpObj[key].push(v);
       }else{
           tmpObj[key]=[v];
       }
    });
    
    //tmpObj
    for( var key in tmpObj){
        var tmpO={}
        tmpO["name"]=key;
        tmpO["nameIdx"]=[];
        for(var i=0;i<tmpObj[key].length;iPP){
            tmpO["nameIdx"].push({"site":tmpObj[key][i]});
        }
        newArr.push(tmpO);
    }
    return newArr;
}
< hr >

may not be needed upstairs, or the following meets the requirements

function s2a(str){
    var arr=[];
    var lastName='';
    str.split(',').forEach(s=>{
        const [name,site] = s.split('-');
        var cit=arr[arr.length-1];
        if(name!=lastName){
            lastName=name;
            cit={name,'nameIdx':[]};
            arr.push(cit);
        }
        cit['nameIdx'].push({site});
        });
    return arr;
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bf1baf-31da3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bf1baf-31da3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?