从两个对象数组基于id的角度打字稿映射新对象

时间:2020-07-16 18:32:50

标签: javascript angular typescript foreach

我有这样的东西

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

上的正确的问题

我的新 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
        }]
}
];

1 个答案:

答案 0 :(得分:0)

您可以尝试将数组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);