不明なオブジェクトのJSON階層構造を作成したいので、再帰的に処理する必要があります。
これが私の関数です。ここでangular.element.isEmptyObject()
、jQueryから継承されangular.copy()
、オブジェクトのディープコピーを作成する関数です(私はAngularJSを使用しています)。
function recurseTree(tree, newKey, newId) {
if(angular.element.isEmptyObject(tree)) {
tree[newKey] = {_id: newId};
} else {
for(var key in tree) {
if(typeof tree[key] == 'object') recurseTree(tree[key], newKey, newId);
else tree[newKey] = {_id: newId};
}
}
return angular.copy(tree);
}
今これを実行します:
var testT = {};
console.log(recurseTree(testT, 'a', '1'));
console.log(recurseTree(testT, 'b', '2'));
console.log(recurseTree(testT, 'c', '3'));
console.log(recurseTree(testT, 'd', '4'));
console.log(recurseTree(testT, 'e', '5'));
1番目と2番目のものが期待どおりに戻ることに気付くでしょう。
{
a: {
_id: '1',
b: {
_id: '2'
}
}
}
しかし、3つ目は私が問題にぶつかったところです。
{
a: {
_id: '1',
b: {
_id: '2',
c: {
_id: '3'
}
},
c: {
_id: '3'
}
}
}
オブジェクトをの子としてではなく、の子としてのみc
追加するには、何を修正する必要がありますか?私は困惑しています。b
a
これが実際のJSFiddleです。コンソールで結果を確認してください。 http://jsfiddle.net/winduptoy/Mjq5D/2/