javascript - 将 javascript 对象键更改为属性值

标签 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' },
};
现在我想创建一个这样的结构
{
    "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/

相关文章:

javascript - 在 javascript 中,将自定义事件附加到文档本身是不好的做法吗?

javascript - Bootstrap 介入 datatable css

javascript - 如何在 JavaScript 中创建抽象基类?

javascript - TO DO APP - 如何将 2 个图标对齐到 li 的右侧?

javascript - 如何将上下文菜单限制为仅针对 Chrome 扩展程序中的某些选定文本显示?

javascript - 如何将小书签转换为 Greasemonkey 用户脚本?

javascript - parent 删除不适用于 append 元素

javascript - 从 Node API 到 PHP 服务器的 Axios 调用导致套接字挂起

javascript - 键值对中的随机变量未解释为变量

javascript - AngularJS 嵌套 jQuery UI 可排序与递归