javascript - 通过唯一字段合并 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
对象)
- 标题:“这是第 1 题”
- 参考“:”data_q1“
答案(answers
对象)
- 参考“:”data_q1“
- 数量:2
因此,对于问题 1(带有 ref: data_q1
),数字(分数)为 2。
我正在尝试做的是将两个问题的答案基于ref
. 我想这样做,以便我可以得到number
. 即问答为data_q1
2。
我有以下内容:
// 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 ===
,我不知道要通过什么,因为问题和答案还没有映射在一起。
解决方案
1) 构建一个 answer_number 对象,其中 ref 作为键,值作为数字 from data.answers
。
2)使用map
overdata.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);
推荐阅读
- math - 朱莉娅提供了错误的数字结果
- typescript - 打字稿错误 TS2304:即使使用 esnext 也找不到名称 AsyncIterator
- android - Android-应用程序没有收到来自解析平台的推送通知
- c# - 生成和打印 Microsoft Word 文件
- python-3.x - 停电前写入外部文件
- soap - 服务器无法处理请求。,对象引用未设置为对象的实例。SOAP API
- java - 日历 set() 在 Android API 23 及更低版本上损坏 - java.util.Calendar
- groovy - 脚本逐行读取文本文件并搜索特定单词并将与该单词相关的所有行复制到远程目录
- javascript - 将用户保存到猫鼬时出现 Bcrypt 错误
- azure - 如何将 Azure 部署与用户关联?