如何在JSON对象中获取下一个键并进行键对比
如何在遍历JSON对象时访问当前键与下一个键
由于Object.entries()返回的是键值对组成的数组,forEach()的回调函数无法直接获取下一个元素,你可以通过以下两种方式实现访问当前键和下一个键的需求:
方法一:使用for循环遍历键值对数组
先将对象转换为键值对数组,再通过索引直接访问当前和下一个元素,这种方式逻辑直观,且能避免越界问题:
const table_0 = { TR4TD1: 'Region\n\n', TR4TD2: 'Actual Generation (MU) during May \n', TR4TD5: 'Actual Generation (MU) during\nApril to May\n\n', TR5TD2: '2019\n', TR5TD3: '2018\n', TR5TD4: '% Growth\n', TR5TD5: '2019\n', TR5TD6: '2018\n', TR5TD7: '% Growth' }; const entries = Object.entries(table_0); // 遍历到倒数第二个元素,避免下一个元素越界 for (let i = 0; i < entries.length - 1; i++) { const [currentKey, currentValue] = entries[i]; const [nextKey, nextValue] = entries[i + 1]; // 在这里执行你需要的对比逻辑 console.log(`当前键: ${currentKey}, 下一个键: ${nextKey}`); }
方法二:在forEach中结合索引判断
如果你更习惯使用forEach(),可以利用回调函数的索引参数,判断当前不是最后一个元素时,获取下一个键值对:
const table_0 = { TR4TD1: 'Region\n\n', TR4TD2: 'Actual Generation (MU) during May \n', TR4TD5: 'Actual Generation (MU) during\nApril to May\n\n', TR5TD2: '2019\n', TR5TD3: '2018\n', TR5TD4: '% Growth\n', TR5TD5: '2019\n', TR5TD6: '2018\n', TR5TD7: '% Growth' }; const entries = Object.entries(table_0); entries.forEach(([currentKey, currentValue], index) => { // 排除最后一个元素,防止访问不存在的下一个元素 if (index < entries.length - 1) { const [nextKey, nextValue] = entries[index + 1]; console.log(`当前键: ${currentKey}, 下一个键: ${nextKey}`); } });
两种方法都能实现你的需求,你可以根据代码习惯选择使用。
内容的提问来源于stack exchange,提问作者AdityaB
相关产品推荐
相关产品推荐

