2016-12-06 56 views
-1

我有一個我想修改的json對象。這是數據:javascript - 修改我的json

var data1 = { 
    "[email protected]": { 
    "[email protected]": { 
     "[email protected]": { 
     "[email protected]": { 
      "[email protected]": {} 
     }, 
     "[email protected]": {} 
     }, 
     "[email protected]": { 
     "[email protected]": {} 
     } 
    }, 
    "[email protected]": {} 
    } 
}; 

基本上每一個密鑰,一個'-'我要添加字符+每個數字的總和在右邊,在右邊的'@'左替換所有'.'。例如,如果密鑰是'[email protected]',我的新密鑰將是'[email protected]'。 這個例子中,我想這是結果:

var data2 = { 
     "[email protected]": { 
     "[email protected]": { 
      "[email protected]": { 
      "[email protected]": { 
       "[email protected]": {} 
      }, 
      "[email protected]": {} 
      }, 
      "[email protected]": { 
      "[email protected]": {} 
      } 
     }, 
     "[email protected]": {} 
     } 
    }; 

可以請你幫忙嗎?

+2

約300個代表,你應該知道怎麼問。如果沒有,請參加[遊覽],並看看[mcve] – mplungjan

+0

考慮按鍵'foreach'遞歸和'sum'函數。 – Anson

回答

2

Here是一個工作小提琴。該代碼是:

var data1 = { 
    "[email protected]": { 
    "[email protected]": { 
     "[email protected]": { 
     "[email protected]": { 
      "[email protected]": {} 
     }, 
     "[email protected]": {} 
     }, 
     "[email protected]": { 
     "[email protected]": {} 
     } 
    }, 
    "[email protected]": {} 
    } 
}; 

console.log(JSON.stringify(fixData(data1))); 

function fixData(data) { 
    var result = {}; 
    for (var key in data) { 
    if (data.hasOwnProperty(key)) { 
     if (key.indexOf("@") == -1) 
     continue; // Ignore keys without @'s 

     var parts = key.split("@"); 
     var left = parts[0]; 
     var right = parts[1]; 

     // Replace .'s with -'s 
     while (right.indexOf(".") > -1) { 
     right = right.replace(".", "-"); 
     } 

     // Add up values 
     var num = 0; 
     var splits = right.split("-"); 
     for (var i = 0; i < splits.length; i++) { 
     var chars = splits[i]; 
     if (!isNaN(chars)) { 
      num += parseInt(chars); 
     } 
     } 
     left += num; 

     // Replace key 
     var existing = data[key]; 
     result[left+"@"+right] = fixData(existing); 
    } 
    } 

    return result; 
} 

這給:

{ 
    "[email protected]":{ 
     "[email protected]":{ 
     "[email protected]":{ 
      "[email protected]":{ 
       "[email protected]":{ 

       } 
      }, 
      "[email protected]":{ 

      } 
     }, 
     "[email protected]":{ 
      "[email protected]":{ 

      } 
     } 
     }, 
     "[email protected]":{ 

     } 
    } 
} 
+0

@dmx這是做你需要的嗎? – JosephGarrone

+0

是的,謝謝 – dmx

+0

'num = right.split(「 - 」)。reduce(function(prev,curr){paramInt(prev,10)+ parseInt(curr,10); } – mplungjan