通过另一对象的键访问嵌套对象属性时遇undefined问题排查
问题描述
现有两个对象,需要通过OutputReference中的键,匹配masterKey的对应键,提取view属性并组成数组:
const OutputReference = {Key1: "Some Random String",Key2: "Some Random String"} const masterKey = { // ...其他属性 'Key1':{ Label: "Key 1", view: [1,2,3], }, 'Key2':{ Label: "Key 2", view: [4,5,6], }, // ...其他属性 }
尝试遍历OutputReference的键值对,提取对应view时遇到问题:masterKey.k返回undefined,但console.log(k)能输出正确的键名(如"Key1")。尝试过多种访问方式均无效,仅直接写masterKey.Key1能获取正确值,但无法适配多键场景。期望最终得到数组[[1,2,3],[4,5,6]]。
错误原因分析
- 遍历方式错误:使用
Object.keys(OutputReference).filter(([k,v])=>{...})时,Object.keys()返回的是键的数组,回调参数是单个键字符串,而非键值对数组。解构[k,v]会导致k取键的第一个字符、v取第二个字符,完全不符合预期。 - 属性访问语法错误:
masterKey.k是字面量访问,会直接查找masterKey中名为"k"的属性,而非变量k的值对应的属性,必须用方括号语法masterKey[k]。JSON.stringify(k)会给字符串添加双引号(如"Key1"变成"\"Key1\""),但masterKey的键是不带引号的字符串,导致匹配失败。- 遍历
masterKey时用masterKey.v同样犯了字面量访问的错误,应改为masterKey[v]。
- 变量作用域错误:在
filter回调内部定义tempArr,每次循环都会重新初始化数组,无法累积结果。
解决方案
方式一:forEach遍历收集
const OutputReference = {Key1: "Some Random String", Key2: "Some Random String"}; const masterKey = { Key1: {Label: "Key 1", view: [1,2,3]}, Key2: {Label: "Key 2", view: [4,5,6]} }; const tempArr = []; // 遍历OutputReference的所有键 Object.keys(OutputReference).forEach(key => { // 先检查masterKey中是否存在该键,避免报错 if (masterKey[key] && masterKey[key].view) { tempArr.push(masterKey[key].view); } }); console.log(tempArr); // 输出: [[1,2,3], [4,5,6]]
方式二:map+filter链式调用(更简洁)
const tempArr = Object.keys(OutputReference) // 过滤掉masterKey中不存在或没有view属性的键 .filter(key => masterKey[key]?.view) // 提取对应view属性 .map(key => masterKey[key].view); console.log(tempArr); // 输出: [[1,2,3], [4,5,6]]
补充:用Object.entries遍历键值对
如果需要同时用到OutputReference的键和值,可以用Object.entries():
const tempArr = []; Object.entries(OutputReference).forEach(([key, value]) => { if (masterKey[key]?.view) { tempArr.push(masterKey[key].view); } });
内容的提问来源于stack exchange,提问作者JoshA328
相关产品推荐
相关产品推荐

