JavaScript/Node.js按JSON键匹配实现嵌套对象深度赋值的方法
JavaScript/Node.js 嵌套JSON按规则提取值实现
实现思路
- 遍历对比规则
compareObj的每一个顶级分类 - 对每个分类,先获取要匹配的目标属性名
- 按顺序遍历该分类下的所有语言层级子对象,再遍历子对象下的所有唯一ID对应的属性集合
- 取第一个存在且值不为null的目标属性值,没有匹配到就赋值为
"Untitled"
完整实现代码
function extractCompareValues(result, compareObj) { const resultMap = {}; // 遍历所有规则中的顶级分类 for (const [category, rule] of Object.entries(compareObj)) { const targetKey = rule.compare; let compareValue = "Untitled"; // 确认result存在对应分类才继续查找 if (result[category]) { // 遍历分类下的所有语言层级子对象 for (const langObj of Object.values(result[category])) { // 遍历语言下的所有唯一ID对应的属性集合 for (const attrObj of Object.values(langObj)) { // 匹配到有效属性直接终止遍历 if (attrObj.hasOwnProperty(targetKey) && attrObj[targetKey] !== null) { compareValue = attrObj[targetKey]; break; } } if (compareValue !== "Untitled") break; } } resultMap[category] = compareValue; } return resultMap; }
测试验证(对应示例场景)
测试输入数据
// 业务数据result示例 const result = { computer: { en: { "id123": { gallery: "Some value here", otherAttr: "test" } }, zh: { "id456": { gallery: "中文值" } } }, testing: { hi: { "id789": { otherKey: "test hi" } }, ja: { "id012": { mediaaccess: "system check" } } }, hardware: { en: { "id345": { fieldtest: null } }, zh: { "id678": { fieldtest: null } } } }; // 对比规则compareObj示例 const compareObj = { computer: { compare: "gallery" }, testing: { compare: "mediaaccess" }, hardware: { compare: "fieldtest" } };
调用与输出
const output = extractCompareValues(result, compareObj); console.log(output); /* 输出结果: { computer: 'Some value here', testing: 'system check', hardware: 'Untitled' } 完全匹配示例场景的预期结果 */
内容的提问来源于stack exchange,提问作者user16041868
相关产品推荐
相关产品推荐

