2016-12-06 5 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

を、あなたが依頼する方法を知っている必要があります。そうでない場合は、[ツアー]と[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; 
} 

これが与える:約300担当者で

{ 
    "[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(" - ")。 return parseInt(prev、10)+ parseInt(curr、10); }}' – mplungjan