You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Object.entries遍历对象获取目标元素及其下一个元素?

解决思路:获取对象中目标值对应的当前与下一个元素

咱们先明确需求:现有对象

const obj = { 1: 10, 2: 20, 3: 30, 4: 40, 5: 50 };

给定数值25,需要通过Object.entries(obj)遍历对象,最终得到{ current: { 2: 20 }, next: { 3: 30 } }——也就是找到值小于25的最后一个元素作为current,同时拿到它的下一个元素作为next。

实现方案

核心思路是利用Object.entries()把对象转成有序的键值对数组(数字键会按升序排列),然后遍历数组找到符合条件的元素对。直接上代码:

const obj = { 1: 10, 2: 20, 3: 30, 4: 40, 5: 50 };
const targetNum = 25;
const entries = Object.entries(obj);
let result = null;

// 遍历键值对数组
for (let i = 0; i < entries.length; i++) {
  const [currentKey, currentValue] = entries[i];
  // 检查当前值小于目标值,且存在下一个元素
  if (currentValue < targetNum && i + 1 < entries.length) {
    const [nextKey, nextValue] = entries[i + 1];
    // 组装成需要的结果格式
    result = {
      current: { [currentKey]: currentValue },
      next: { [nextKey]: nextValue }
    };
  }
}

console.log(result); // 输出:{ current: { '2': 20 }, next: { '3': 30 } }

代码解释

  • Object.entries(obj)会把对象转换为[['1',10], ['2',20], ['3',30], ['4',40], ['5',50]]这样的数组,数字键会自动按升序排列,刚好符合咱们的遍历需求
  • 遍历过程中,每次判断当前值是否小于25,同时确保下一个元素存在(避免数组越界)
  • 因为是顺序遍历,最后一次满足条件的元素就是最接近25的那个(也就是值为20的元素),对应的下一个元素就是值为30的元素,最终组装成你想要的结果格式

如果想要更简洁的写法,也可以用数组的reduce方法来实现,效果是一样的:

const result = entries.reduce((acc, [key, value], index) => {
  if (value < targetNum && index + 1 < entries.length) {
    return {
      current: { [key]: value },
      next: { [entries[index+1][0]]: entries[index+1][1] }
    };
  }
  return acc;
}, null);

内容的提问来源于stack exchange,提问作者Sqveeze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:07:48