You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaScript对象的键替换为question_id属性值?对象数组与对象型对象的结构转换实现

解决方案:生成以question_id为键的合并对象

我来帮你搞定这个问题!你现在的代码已经能成功匹配到对应的title,但问题出在没有把question_id作为新对象的键,而是一直在修改原state_question的结构。我们需要创建一个全新的对象,把每个条目用对应的question_id来索引,同时合并title属性。

完整实现代码

const state_checklist = [
 { id: '1', title: 'Q1', question_id: 'CuaQV', },
 { id: '2', title: 'Q3', question_id: 'XKVbQ', },
 { id: '3', title: 'Q2', question_id: 'zmId1', },
];
const state_question = {
 2: { answer: 'yes', comments: '', question_id: 'CuaQV' },
 3: { answer: 'no', comments: '', question_id: 'zmId1' },
};

// 初始化空的结果对象
const finalResult = {};

// 遍历state_question的所有条目
for (const key in state_question) {
  if (state_question.hasOwnProperty(key)) {
    const currentQuestion = state_question[key];
    // 获取当前条目的question_id作为新对象的键
    const targetKey = currentQuestion.question_id;
    // 从checklist中找到对应的title
    const matchedItem = state_checklist.find(q => q.question_id === targetKey);
    
    // 组合属性并添加到结果对象中
    finalResult[targetKey] = {
      ...currentQuestion, // 快速复制原有的answer、comments、question_id
      title: matchedItem.title // 补充对应的title
    };
  }
}

console.log(finalResult);

代码说明

  1. 创建新对象:我们没有直接修改原state_question,而是新建了finalResult来存储最终结构,避免污染原始数据。
  2. 替换键名:用每个条目自身的question_id(即targetKey)作为新对象的键,而不是原state_question中的数字键(2、3)。
  3. 合并属性:使用扩展运算符...快速复制原条目的所有属性,再补充从state_checklist中匹配到的title,写法更简洁。

更简洁的写法(推荐)

如果不想用for...in,可以用Object.values()直接遍历state_question的所有值,代码更现代:

const finalResult = {};

Object.values(state_question).forEach(questionItem => {
  const targetKey = questionItem.question_id;
  const matchedItem = state_checklist.find(q => q.question_id === targetKey);
  
  if (matchedItem) {
    finalResult[targetKey] = {
      ...questionItem,
      title: matchedItem.title
    };
  }
});

运行上面的代码后,finalResult就是你想要的结构:

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

内容的提问来源于stack exchange,提问作者Jerome Taylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:57:29