简体   繁体   English

Go 到 arrays 个对象,其中包含 arrays 个对象

[英]Go through arrays of objects that contain arrays of objects

Backend sends an object that contains an array of objects.后端发送一个包含对象数组的 object。 These objects contain more arrays of objects and so on.这些对象包含更多 arrays 的对象等等。 It resembles a tree.它像一棵树。

I need to be able to go from one object to the other, following the array, and back.我需要能够 go 从一个 object 到另一个,跟随数组,然后返回。 What would be the best way to do this in typescript?在 typescript 中执行此操作的最佳方法是什么?

I tried forEach, but I couldn't go back.我尝试了 forEach,但无法返回 go。 For cycles inside of for cycles aren't an option either because sometimes there will be 2 levels of arrays, sometimes, 5. I thought of an iterator, but I don't know enough of angular/typescript to make it happen. For cycles inside for cycles 也不是一个选项,因为有时会有 2 级 arrays,有时是 5 级。我想到了一个迭代器,但我对 angular/typescript 的了解还不够多,无法实现它。

Here is a snippet of the data.这是数据的一个片段。 This is a questionnaire and I need to show each question individually.这是一份问卷,我需要单独展示每个问题。

"questionId": 1,
"parent": null,
"description": "Question 1?",
"children": 
[
    {
        "questionId": 2,
        "parent": 1,
        "description": "Question 2?",
        "children": 
        [
            {
                "questionId": 4,
                "parent": 2,
                "description": "Question 4?",
                "children": []
            }
        ]

    },
    {
        "questionId": 3,
        "parent": 1,
        "description": "Question 3?",
        "children": []
    }
]

Sorry if I'm explaining it poorly or something is missing, I'm not used to post here.抱歉,如果我解释得不好或遗漏了什么,我不习惯在这里发帖。

If you just want to iterate through all the question objects, you could try to flatten your data with a recursive function like this,如果您只想遍历所有问题对象,您可以尝试使用这样的递归 function 来展平数据,

const flattenQs = (qData) => {
  const flattenedQs = []
  flattenedQs.push({questionId: qData.questionId, parent: qData.parent, description: qData.description})
  for (let i = 0; i < qData.children.length; i++) {
    const qChild = qData.children[i];
    flattenedQs.push(...flattenQs(qChild))
  }
  return flattenedQs
}

Which would give something like this,这会给这样的东西,

[
  {
    questionId:1,
    parent:null,
    description:"Question 1?"
  },
  {
    questionId:2,
    parent:1,
    description:"Question 2?"
  },
  {
    questionId:4,
    parent:2,
    description:"Question 4?"
  },
  {
    questionId:3,
    parent:1,
    description:"Question 3?"
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM