将JavaScript对象键更改为属性值

5
我有两个变量,一个是对象数组,另一个是对象的集合。
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);

我认为你应该在代码的数据结构和意图方面提供更多细节。 - Malik Bagwala
1
你的示例是否正确?state_question zmId1 - 回答 - 不是,期望结果是回答为“是”。 - ProDec
亚和给出的答案对我来说似乎还不错。我正在尝试实现类似的东西。 - Jerome Taylor
2个回答

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


0

基本上,使用Object.values(state_question)生成的数组的reduce函数可以得到一个更短的答案,并按以下方式组成对象(从{}开始):

const result = Object.values(state_question).reduce((acc, val) => ({
        ...acc,
        [val.question_id]: {
          // ...state_checklist.find(item => item.question_id === val.question_id),
          title: state_checklist.find(item => item.question_id === val.question_id).title,
          ...val,
        }
    }), {});

console.log(result);

// { CuaQV: { question_id: 'CuaQV', title: 'Q1', answer: 'yes', comments: '' },
//   zmId1: { question_id: 'zmId1', title: 'Q2', answer: 'no', comments: '' } 
// }

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何撰写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接