如果我明白你的問題(我不知道),我會用不同的策略來解決問題。
如你所知,JSON對象不具有的屬性,但只是孩子們的屬性。您可以使用名爲child
的屬性來存儲父對象的子對象(子樹)。
var parent = {
"value": "Parent own value",
"child": {
"grandchild": {"value": "ValueGrandChild", "child": {}}
"anotherchild": {"value": "anotherChildValue", "child": {}}
}
};
兒童和屬性是更好的分離,就可以解決這些問題(和「正確」的對象屬性)如下:
parent.child.grandchild.value // returns "valueGrandChild"
parent.value // returns "Parent own value"
你可以有也有一些其他商品:
var how_many_child = Object.keys(parent.child).length
var a_child = parent.child.anotherchild
var how_many_nephew = Object.keys(a_child.child).length
a_chid.value; // returns "anotherChildValue"
parent.child.anotherchild.value; // returns "anotherChildValue"
是的,這是可能的 – Vineet
oke,你可以說怎麼樣? –
在我看來,我們正在努力靠自己的努力,事情也可以更容易工作。我不確定你的代碼結構是什麼,你是循環還是手動創建。但只記住一件事,你必須按照這樣的順序分配值,以便你可以隨意取回。您可以使用循環或靜態分配。試試這個'parent ['child'] ='valuechild'; parent ['child'] ['grandchild'] ='grandvaluechild';'您也可以在對象中使用'['']'符號 – Vineet