[英]How to recursively loop through nested array of objects that point to other arrays of object?
我有来自 API 的以下 JSON 响应。 我的目标是遍历example_terms
数组中的每个term
键并获取所有$id
值并返回所有值的最终数组,包括每个term_parents
数组中的 id。 所以我的最终结果将类似于: ['taxonomy/24232', 'taxonomy/11179', 'taxonomy/12058', 'taxonomy/11053', etc..]
。 每个term
对象的深度是可变的,所以我知道我必须以某种方式递归地执行此操作。 我不知道如何正确地做到这一点,所以任何帮助表示赞赏。
example_terms: [
{
rejected: false,
term: {
$id: "taxonomy/24232",
term_parents: [{
$id: "taxonomy/15197",
term_parents: [{
$id: "taxonomy/11179",
term_parents: [{
$id: "taxonomy/11013"
}]
}]
}],
}
},
{
rejected: false
term: {
$id: "taxonomy/12058",
term_parents: [{
$id: "taxonomy/12110",
term_parents: [{
$id: "taxonomy/12178",
term_parents: [{
$id: "taxonomy/11013"
}]
}]
}],
}
},
{
rejected: false
term: {
$id: "taxonomy/10769",
term_parents: [{
$id: "taxonomy/11401",
term_parents: [{
$id: "taxonomy/11807",
term_parents: [{
$id: "taxonomy/11374",
term_parents: [{
$id: "taxonomy/11053"
}]
}]
}]
}],
}
}
]
您可以查看对象并获取所需的属性和嵌套值或返回一个空数组。
这种方法的特点是一个数组。 这是可扩展的,并且允许递归函数而无需存储中间结果。
让我们从退出条件开始。 这是对不是真实值和没有对象的检查。 然后返回一个空数组(此检查在下面颠倒)。
对于作为对象的真值,也检查所需的键,如果找到则获取值,否则获取空数组进行传播。
然后从对象中获取值并使用它制作平面地图。 此调用的结果将传播到结果数组以供返回。
function getValues(object) { return object && typeof object === 'object' ? [ ...('$id' in object ? [object.$id] : []), ...Object.values(object).flatMap(getValues) ] : []; } var data = { example_terms: [{ rejected: false, term: { $id: "taxonomy/24232", term_parents: [{ $id: "taxonomy/15197", term_parents: [{ $id: "taxonomy/11179", term_parents: [{ $id: "taxonomy/11013" }] }] }] } }, { rejected: false, term: { $id: "taxonomy/12058", term_parents: [{ $id: "taxonomy/12110", term_parents: [{ $id: "taxonomy/12178", term_parents: [{ $id: "taxonomy/11013" }] }] }] } }, { rejected: false, term: { $id: "taxonomy/10769", term_parents: [{ $id: "taxonomy/11401", term_parents: [{ $id: "taxonomy/11807", term_parents: [{ $id: "taxonomy/11374", term_parents: [{ $id: "taxonomy/11053" }] }] }] }] } }] }, result = getValues(data); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.