1. 程式人生 > >json物件相同key合併value值

json物件相同key合併value值

 var s = '{"身高":"175cm","性別":"男","興趣":"唱歌","興趣":"棒球","興趣":"游泳"}'
    var kv = {}, m, reg = /"[^"]+":"[^"]+"/gi;
    var m = s.match(reg);

    var o={};
    for(var i=0;i<m.length;i++){
        kv=m[i].match(/"[^"]+"/gi);
         var _arr1=[];;
        for(var j=0;j<kv.length; j++){
            _arr1.push(kv[j].replace(/"
/g,'')); } if(_arr1[0] in o){ if(typeof(o[_arr1[0]])=='string') { o[_arr1[0]]=[o[_arr1[0]]] }; o[_arr1[0]].push(_arr1[1]) }else{ o[_arr1[0]]=_arr1[1] } } console.log(o)//'{"身高":"175cm","性別":"男","興趣":["唱歌,"棒球","游泳"]}'