Skip to content

Change javascript object key to property value

I have two variable like this, one is array of objects and one is object of objects

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' },
};

Now I want to create a structure like this

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

where key should be question_id

Code that I have tried to generate that object is below, here I am unable to create the question_id as key, else everything is seems ok for me.

//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);

Answer

You can loop through your checklist and then map the values to an object and look up the other object array values with what exist there and missed in your result

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