[英]Loop array according how deep it is
好吧,首先抱歉,如果标题不能很好地解释这个问题,我不知道该如何称呼它,因此我有一系列对象,如下所示:
"$type": "EnumerationElementDTO",
"Style": "Number",
"Id": "c59d36e2-2a60-4223-82f3-d48a22140655",
"Content": ["4f2a412c-2f46-4463-8855-1ae320074811", {
"$type": "ElementDTO",
"Id": "9784a5eb-cafb-4193-8aeb-f431cae8e69e",
"Content": ["e5c7bb45-3bb0-40bd-a3a2-1fbf847124fd", {
"$type": "EnumerationElementDTO",
"Style": "Number",
"Id": "84fa3127-54da-4ccf-99e0-fa25ca50faca",
"Content": ["9f68bc57-d42c-4cd7-94bd-a3905a5d9b82", {
"$type": "ElementDTO",
"Id": "ab55aaaf-decc-4cd4-9652-8c7ef4f51ec7",
"Content": ["3a5242e5-1a26-4444-b072-bc34a62db161", {
"$type": "EnumerationElementDTO",
"Style": "Disc",
"Id": "7957bca7-34ea-4962-a662-be68e1097ac2",
"Content": ["ffacd2c4-8029-442c-b6c6-8bf99606ec10", "5558f28a-9dc8-401a-a1fe-381202163250"]
}]
}, "8077515c-bc10-4102-9bf9-17593d4831e9"]
}]
}, {
"$type": "ElementDTO",
"Id": "400b94c9-ae0f-46da-967a-1bf5854983c6",
"Content": ["2d26fa94-2457-4d7c-baf1-5660a0a81046", {
"$type": "EnumerationElementDTO",
"Style": "Disc",
"Id": "b690c3d5-47aa-4788-ba67-d20546f98a10",
"Content": ["86f1fb17-8516-403f-b5ff-0150f444e373", {
"$type": "ElementDTO",
"Id": "88b193a7-4978-4e91-9b14-ff483c0c2bc1",
"Content": ["984f37c4-045b-4ce7-bca7-32ba72cb4f08", {
"$type": "EnumerationElementDTO",
"Style": "Number",
"Id": "57e3a868-4e67-4b58-88b0-3dff9ea7ed1d",
"Content": ["f485dc2a-8871-4d23-a688-823ea7f4bb87", {
"$type": "ElementDTO",
"Id": "2729ee34-de7a-4a90-9a11-7824a776e4b6",
"Content": ["5112151d-6f56-4fec-8f39-8c6d757a3145", {
"$type": "EnumerationElementDTO",
"Style": "Number",
"Id": "c9a7ef3f-ae36-4afb-ab47-fbf430f342e3",
"Content": ["04d00a01-b142-47d1-bc09-b5076b8a3824", "343d7b69-a9ae-4121-bf94-75c1e70a835c"]
}]
}]
}]
}, "501609f9-9a64-4c93-aac5-d86e387c882b"]
}]
}]
现在,我需要循环作为数组的对象的属性"content"
,如您所见,有时数组上的元素是字符串或对象,因此我循环了数组"content"
并创建了一个条件来检查数组的类型元素,如果元素是字符串类型,则对它做一些操作,如果是,则对象进入对象内部,并循环该对象的"content"
属性,并再次执行相同的过程,现在最大深度为9深入,最简单的方法是为每个阵列级别示例创建一个循环:
object.content.forEach((e) => {
if(typeof e === 'string') {
// Do something here with the string
}else {
e.content.forEach((c => {
if(typeof c === 'string') {
// Do something here with the string
} else {
c.content.forEach((d) => {
if(typeof d === 'string') {
// Do something here with the string
} else {
d.content.forEach((f) => {
if(typeof f === 'string') {
// Do something here with the string
} else {
}
});
}
});
}
});
}
});
问题是,有没有办法以最佳的方式做到这一点,直到达到物体的9个深度?
您可以去做所需的if / else检查数量。
但是代码将很难理解和维护。
您可以使用递归,关于这个主意,请查看修改后的代码段:
function handleElement(e) {
if(typeof e === 'string') {
// Do something here with the string
}else {
e.content.forEach(handleElement);
}
}
object.content.forEach(handleElement);
Wikipedia上的递归: https : //en.wikipedia.org/wiki/Recursion_(computer_science)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.