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

JavaScript如何将对象数组中pending状态属性拆分为独立对象数组

JavaScript对象数组转换实现

你可以直接使用Array.prototype.flatMap结合属性遍历实现需求,代码如下:

// 原数组
const sourceArr = [
  {
    id: 1,
    checkInStatus: 'pending',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 2,
    checkInStatus: 'success',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 3,
    checkInStatus: 'pending',
    overtimeStatus: 'success',
    checkOutStatus: 'success'
  }
];

// 转换逻辑
const targetArr = sourceArr.flatMap(item => {
  const pendingList = [];
  // 遍历当前对象所有键值对
  Object.entries(item).forEach(([key, value]) => {
    // 排除id字段,筛选值为pending的属性
    if (key !== 'id' && value === 'pending') {
      pendingList.push({ id: item.id, [key]: value });
    }
  })
  return pendingList;
})

console.log(targetArr);

逻辑说明

  • flatMap方法会在遍历原数组的同时,自动将每个元素返回的子数组合并为一维数组,无需额外做扁平化处理
  • 用Object.entries遍历对象的键值对,筛选出非id且值为pending的属性
  • 每匹配到一个符合要求的属性,就生成一个携带原id的新对象,最终汇总得到目标数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:45:06