将 javascript 对象键更改为属性值

Jer*_*lor 5 javascript

我有两个这样的变量,一个是对象数组,一个是对象对象

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' },
};
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个像这样的结构

{
    "zmId1": {
        "answer": "yes",
        "comments": "",
        "question_id": "zmId1",
        "title": "Q2"
    },
    "CuaQV": {
        "answer": "no",
        "comments": "",
        "question_id": "CuaQV",
        "title": "Q1"
    }
}
Run Code Online (Sandbox Code Playgroud)

其中 key 应该是 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);
Run Code Online (Sandbox Code Playgroud)

Oba*_*san 2

您可以循环检查清单,然后将值映射到一个对象,并查找其他对象数组值以及结果中存在和遗漏的值

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: '' } 
// }

Run Code Online (Sandbox Code Playgroud)