【问题标题】:Map new object from two objects array angular typescript baesed on id基于 id 从两个对象数组角度打字稿映射新对象
【发布时间】:2020-07-16 18:32:50
【问题描述】:

我有这样的事情

export class Question {
  id: string;
  title: string;
  description: string;
  answers: Answer[];
}

export class Answer {
  id: string;
  text: string;
  questionId: string;
}

我有两个这样的对象

answers =  [
    {
      "id": 1,
      "text": "some comment1",
      "questionId": 1
    },
    {
      "id": 2,
      "text": "some comment2",
      "questionId": 3
    },
    {
      "id": 3,
      "text": "some comment3",
      "questionId": 3
    }
  ];

questions = [
    {
      "id": 1,
      "title": "Name1",
      "description": "typicode1"
    },
    {
      "id": 2,
      "title": "Name2",
      "description": "typicode2"
    },
    {
      "id": 3,
      "title": "Name3",
      "description": "typicode3"
    }
  ];

questionsAndAnswers: Question[];

现在我需要将答案映射到属性 answers

上的正确 question

我的新 questionsAndAnswers 应该是这样的

questionsAndAnswers = [{
      id: 1,
      title: Name1,
      description: typicode1;
      answers: [{
          "id": 1,
          "text": "some comment1",
          "questionId": 1
        }]
},
{
      id: 2,
      title: Name2,
      description: typicode2;
      answers: []
},
{
      id: 3,
      title: Name3,
      description: typicode3;
      answers: [{
          "id": 2,
          "text": "some comment2",
          "questionId": 3
        },
{
          "id": 3,
          "text": "some comment3",
          "questionId": 3
        }]
}
];

【问题讨论】:

  • 你试过什么?您是否考虑过在您的 answers 数组中使用 .filter 来获得特定问题的答案?
  • 我什至不知道如何开始,我必须先提出问题,然后再回答内部问题吗?

标签: javascript angular typescript foreach


【解决方案1】:

您可以尝试将数组reducefilter 函数一起使用。试试下面的

var questions = [ { "id": 1, "title": "Name1", "description": "typicode1" }, { "id": 2, "title": "Name2", "description": "typicode2" }, { "id": 3, "title": "Name3", "description": "typicode3" } ];
var answers =  [ { "id": 1, "text": "some comment1", "questionId": 1 }, { "id": 2, "text": "some comment2", "questionId": 3 }, { "id": 3, "text": "some comment3", "questionId": 3 } ];
  
var questionsAndAnswers = questions.reduce((acc, curr, index) => {
  acc[index] = curr;
  acc[index].answers = answers.filter(answer => answer.questionId === curr.id);
  return acc;
}, []);

console.log(questionsAndAnswers);

【讨论】:

  • 这个很好用,我从来没有用过reduce,谢谢,你能在map和foreach上给出答案吗,我能理解,因为我需要学习,这对我来说太复杂了:(跨度>
  • 我会说最好了解reduce函数。它几乎适用于所有主要语言。通过在内部打印变量 acccurr 并查看它如何遍历数组可能更容易开始。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2021-10-31
  • 2019-04-11
  • 2020-08-06
  • 2020-06-25
  • 2020-07-29
  • 2019-06-18
  • 2021-02-24
相关资源
最近更新 更多