我有两个变量,一个是对象数组,另一个是对象的集合。
现在我想创建这样的结构。
let state_checklist = [
{
id: '1',
title: 'Q1',
question_id: 'CuaQV',
},
{
id: '2',
title: 'Q3',
question_id: 'XKVbQ',
},
{
id: '3',
title: 'Q2',
question_id: 'zmId1',
},
];
let state_question = {
2: { answer: 'yes', comments: '', question_id: 'CuaQV' },
3: { answer: 'no', comments: '', question_id: 'zmId1' },
};
现在我想创建这样的结构。
{
"zmId1": {
"answer": "yes",
"comments": "",
"question_id": "zmId1",
"title": "Q2"
},
"CuaQV": {
"answer": "no",
"comments": "",
"question_id": "CuaQV",
"title": "Q1"
}
}
键名应该是question_id。
我尝试生成该对象的代码如下,但我无法将question_id创建为键名,除此之外,一切看起来都很好。
//var obj = {};
for (var key in state_question) {
if (state_question.hasOwnProperty(key)) {
//var key = state_question[key]['question_id'];
const questionid = state_question[key]['question_id'];
const title = state_checklist.find(
(q) => q.question_id == questionid
).title;
state_question[key]['title'] = title;
//obj[key] = state_question[key];
console.log(title);
}
}
console.log(state_question);
state_question
zmId1 - 回答 - 不是,期望结果是回答为“是”。 - ProDec