如何在JavaScript中提取嵌套JSON结构中的键值对?
提取嵌套JSON结构中的键值对
首先注意你的content字段是JSON字符串,不是直接可操作的JavaScript对象,这是你遍历无效的核心原因。按以下步骤就能提取目标键值对:
步骤1:解析JSON字符串为JS对象
先用JSON.parse()把content里的字符串转换成可操作的对象:
// 假设你的原始数据存在response变量里 const response = { statusCode: 200, content: '{"X":{"key":"k","name":"n", "nested":[{"nestedValue":"A","value":"111"},{"nestedValue":"B","value":"222"},{"nestedValue":"3","value":"333","bestValue":false}]}}', headers: {} }; // 解析content字符串 const parsedContent = JSON.parse(response.content);
步骤2:定位到嵌套数组
从解析后的对象里找到X.nested数组:
const nestedArray = parsedContent.X.nested;
步骤3:遍历数组提取目标键值对
遍历数组,把每个元素的nestedValue作为键,value作为值,存入对象或直接输出:
// 方法1:存入对象保存结果 const result = {}; nestedArray.forEach(item => { result[item.nestedValue] = item.value; }); console.log(result); // 输出 { A: '111', B: '222', '3': '333' } // 方法2:直接遍历输出目标配对 nestedArray.forEach(item => { console.log(`${item.nestedValue}:${item.value}`); }); // 输出: // A:111 // B:222 // 3:333
额外提示
如果只需要A和B这类非数字开头的键,可以加个过滤条件:
const filteredResult = {}; nestedArray.forEach(item => { // 筛选nestedValue为字母的项 if (/^[A-Za-z]+$/.test(item.nestedValue)) { filteredResult[item.nestedValue] = item.value; } }); console.log(filteredResult); // 输出 { A: '111', B: '222' }
内容的提问来源于stack exchange,提问作者user20330985
相关产品推荐
相关产品推荐

