我从我的REST-Api中得到一个像这样的对象
var newObj = {
array1: [
{
"elm": 1, children: [
{"elm": 2},
{"elm": 3},
{"elm": 4},
{"elm": 5}
]
}
],
array2: [
{
"elm": 6, children: [
{"elm": 7},
{"elm": 8},
{"elm": 9},
{"elm": 10}
]
}
]
};
由于更改了界面并且无法访问api及其structurebuild,我必须将对象解析为以下内容:
DisplayObject(DeckOfPlayingCards, centerX, -90, "DeckOfPlayingCards")
是否有更简单的方法来解决对象而不会遍历每个孩子?
答案 0 :(得分:1)
也许这对你有用......
var obj = { array1: [{ "elm": 1, children: [{ "elm": 2, children: [{ "elm": 3, children: [{ "elm": 4, children: [{ "elm": 5 }] }] }] }] }], array2: [{ "elm": 6, children: [{ "elm": 7, children: [{ "elm": 8, children: [{ "elm": 9, children: [{ "elm": 10 }] }] }] }] }] },
result = function (object) {
function dig(a) {
this.push({ elm: a.elm });
Array.isArray(a.children) && a.children.forEach(dig, this);
}
var r = {};
Object.keys(object).forEach(function (k) {
object[k].forEach(function (a) {
var array = [];
r[k] = r[k] || [];
r[k].push({ elm: a.elm, children: array });
Array.isArray(a.children) && a.children.forEach(dig, array);
});
});
return r;
}(obj);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');