Node.js/JavaScript提取动态键JSON的log字段存入数组
动态键名JSON提取log字段实现方案
场景说明
待处理的JSON对象顶层键名(如user_1/user_2/user_3)为动态生成,无固定取值规则,每个顶层键对应的值为包含id/log/name/address字段的用户信息对象,需要在JavaScript/Node.js环境下提取所有子项的log字段,组装为结构如["de-data","ex-file","dis-acta"]的结果数组。
示例源数据结构:
const userJsonObject = { user_1: { id: 1, log: "de-data", name: "Zhang", address: "addr1" }, user_2: { id: 2, log: "ex-file", name: "Li", address: "addr2" }, user_3: { id: 3, log: "dis-acta", name: "Wang", address: "addr3" } };
实现代码
- 推荐写法(ES2017+ 全支持,Node.js 7.0及以上版本可直接使用)
通过Object.values()直接获取对象所有顶层属性的值,跳过动态键名的处理逻辑,再遍历取值即可:
const gotLog = Object.values(userJsonObject).map(item => item.log);
- 低版本兼容写法
适配不支持Object.values()的老旧运行环境,通过遍历键名取值:
const gotLog = []; for (const dynamicKey in userJsonObject) { // 过滤原型链继承属性,只处理对象自身的属性 if (userJsonObject.hasOwnProperty(dynamicKey)) { gotLog.push(userJsonObject[dynamicKey].log); } }
异常兼容
如果业务场景中可能存在部分用户项缺失log字段的情况,可以加空值兜底,避免结果中出现undefined:
const gotLog = Object.values(userJsonObject) .map(item => item.log ?? '') .filter(Boolean); // 可选:过滤掉空log值
执行以上代码后,最终得到的
gotLog数组即为目标格式的结果。
内容的提问来源于stack exchange,提问作者Arun Yadav
相关产品推荐
相关产品推荐

