如何将数组对象的键替换为嵌套对象中对应标题并返回数组对象
问题:根据嵌套配置替换对象数组的键名
我有一个对象数组arr1,还有一个包含嵌套config数组的对象arr2。需要将arr1中每个对象的键,替换为arr2.config下所有questions数组中,与该键匹配的id对应的custom.title属性值。
示例:arr1中的键isWorking与arr2.config[0].questions[0].id的值相同,因此将isWorking键替换为arr2.config[0].questions[0].custom.title的值。
示例代码
var arr1 = [ {"jobs": "Marketing","isWorking": yes,"country": "MY"}, {"country": "IN","members": 4} ] var arr2 = { "id":1, "name":"xxx", "config":[ { "questions":[ { "id":"isWorking", "custom":{ "title":"Are you working?" } }, { "id":"jobs", "custom":{ "title":"Please specify job(s)" } } ] }, { "questions":[ { "id":"country", "custom":{ "title":"which Country?" } }, { "id":"members", "type":"choices", "custom":{ "title":"How many members?" } } ] } ] }
预期输出
[ {"Please specify job(s)": "Marketing","Are you working?": yes,"which Country?": "MY"}, {"which Country?": "IN","How many members?": 4} ]
我尝试的代码
var result = arr1.map(e => ({ arr2.config.find(i => { i.questions.find( q => { q.id === Object.key(e) ? Object.key(e) === q.custom.title : q.id } }) }))
解决方案
你的尝试代码存在语法错误(比如Object.key应为Object.keys),且逻辑无法正确生成目标对象。正确的做法是先构建一个id到title的映射表,再批量替换键名,这样效率更高:
// 构建id与custom.title的映射表 const keyMap = {}; arr2.config.forEach(configItem => { configItem.questions.forEach(question => { keyMap[question.id] = question.custom.title; }); }); // 遍历arr1替换键名 const result = arr1.map(obj => { const newObj = {}; Object.entries(obj).forEach(([key, value]) => { // 若找不到对应映射则保留原键,可根据需求调整 const newKey = keyMap[key] || key; newObj[newKey] = value; }); return newObj; }); console.log(result);
代码说明
- 构建映射表:遍历
arr2中所有嵌套的questions,把每个id对应的custom.title存入keyMap,后续查找键名映射只需O(1)时间。 - 替换键名:用
Object.entries拆分arr1中每个对象的键值对,通过keyMap获取新键名,组装成新对象返回。
运行这段代码后,输出结果与预期一致。
内容的提问来源于stack exchange,提问作者code44
相关产品推荐
相关产品推荐

