我有两个这样的变量,一个是对象数组,一个是对象的对象
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);
最佳答案
您可以遍历您的 list ,然后将值映射到一个对象并查找其他对象数组值与那里存在的内容并在您的结果中遗漏
const questions = {};
for (const q of state_checklist) {
const answerFound = Object.values(state_question).find(x => q.question_id === x.question_id);
if (answerFound) {
questions[q.question_id] = {
question_id: q.question_id,
title: q.title,
answer: answerFound.answer,
comments: answerFound.comments
}
}
}
// Result
// { CuaQV: { question_id: 'CuaQV', title: 'Q1', answer: 'yes', comments: '' },
// zmId1: { question_id: 'zmId1', title: 'Q2', answer: 'no', comments: '' }
// }
关于javascript - 将 javascript 对象键更改为属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69630675/