我收到一个有效载荷,需要从有效载荷内的两个单独级别中提取ID,并将其作为键值对的单个对象返回。我试图进行某种组合或ForEach()reduce(),但似乎找不到正确的方法。这是数据的样子。

{
 orderId:999,
 menuId: 123456,
  questions:[{
    questionId: 123,
    depth: 1,
        answers: [
            { answerId: 999, text: "foo1" },
            { answerId: 888, text: "foo2" }]
  },
  {
    questionId: 654,
    depth: 1,
    answers: [{ answerId: 777, text: "bar" }]
  }]
}


结果是我想要的

{"q_123": ["999", "888"], "q_654": "777"}

最佳答案

使用reduce的以下方法将完成此任务:



const data = {
  orderId: 999,
  menuId: 123456,
  questions: [{
      questionId: 123,
      depth: 1,
      answers: [{
          answerId: 999,
          text: "foo1"
        }, {
          answerId: 888,
          text: "foo2"
        }
      ]
    }, {
      questionId: 654,
      depth: 1,
      answers: [{
        answerId: 777,
        text: "bar"
      }]
    }
  ]};

const result = data.questions.reduce((all, {
  questionId: id,
  answers
}) => {

  all[`q_${id}`] = answers.map(a => a.answerId);

  return all;
}, {});
console.log(result);

10-06 15:25