首页 > 解决方案 > 通过唯一字段合并 JSON 对象,然后打印子节点数据

问题描述

我有以下 JSON:

data: {
    questions: "[{"id":"vzDDWL3GQvJi","title":"This is question 1","type":"opinion_scale","ref":"data_q1","properties":[]},{"id":"okT0ieWJm74d","title":"This  is question 2","type":"opinion_scale","ref":"data_q2","properties":[]},

    answers: "[{"type":"number","number":2,"field":{"id":"vzDDWL3GQvJi","type":"opinion_scale","ref":"data_q1"}},{"type":"number","number":4,"field":{"id":"okT0ieWJm74d","type":"opinion_scale","ref":"data_q2"}},

    createdDate: "2020-02-14T07:43:02.000000Z"
}

上面的一个整洁的版本是:

问题questions对象)

答案answers对象)

因此,对于问题 1(带有 ref: data_q1),数字(分数)为 2。

我正在尝试做的是将两个问题的答案基于ref. 我想这样做,以便我可以得到number. 即问答为data_q12。

我有以下内容:

// Get questions
var questionData = data.data.questions;
var questions = JSON.parse(questionData);

// get answers
var answerData = data.data.answers;
var answers = JSON.parse(answerData);

我试过的:

var answersInfo = answers.map( function(order) {
if( answers.ref === "RefIDHere"){
     var info = { "number": answers.number}
     return info;
 }
});
console.log(answersInfo);

但是,上面的问题是answers.ref ===,我不知道要通过什么,因为问题和答案还没有映射在一起。

标签: javascriptarraysjson

解决方案


1) 构建一个 answer_number 对象,其中 ref 作为键,值作为数字 from data.answers
2)使用mapoverdata.questions并从上面添加数字值。希望这可以帮助。

const data = {
  questions: [
    {
      id: "vzDDWL3GQvJi",
      title: "This is question 1",
      type: "opinion_scale",
      ref: "data_q1",
      properties: []
    },
    {
      id: "okT0ieWJm74d",
      title: "This  is question 2",
      type: "opinion_scale",
      ref: "data_q2",
      properties: []
    }
  ],
  answers: [
    {
      type: "number",
      number: 2,
      field: { id: "vzDDWL3GQvJi", type: "opinion_scale", ref: "data_q1" }
    },
    {
      type: "number",
      number: 4,
      field: { id: "okT0ieWJm74d", type: "opinion_scale", ref: "data_q2" }
    }
  ],
  createdDate: "2020-02-14T07:43:02.000000Z"
};

const answers_number = data.answers.reduce(
  (acc, curr) => Object.assign(acc, { [curr.field.ref]: curr.number }),
  {}
);

const questions_count = data.questions.map(que => ({
  ...que,
  number: answers_number[que.ref]
}));

console.log(questions_count);


推荐阅读