使用 JavaScript 根据 Array 对象中的出现次数计算值

count the values based on number of occurrences in the array object using javascript

提问人:learntocode2468 提问时间:6/18/2023 最后编辑:David Thomaslearntocode2468 更新时间:6/18/2023 访问量:28

问:

我有对象数组,使用 JavaScript 计算状态

如果对象仅启动/仅进度/已启动、进度/已启动或进度已完成、已取消的组合 被视为started_progress计数

如果对象已完成,则仅视为已完成计数

如果对象已取消,则仅视为已取消的计数

如果对象已完成,则一起取消仅视为已完成计数

我试过:

var arrobj = [{
    id: 22,
    details: [{
        status: "started"
      },
      {
        status: "cancelled"
      }
    ]
  },
  {
    id: 24,
    details: [{
        status: "completed"
      },
      {
        status: "cancelled"
      }
    ]
  },
  {
    id: 44,
    details: [{
      status: "progress"
    }]
  },
  {
    id: 54,
    details: [{
        status: "progress"
      },
      {
        status: "completed"
      }
    ]
  },
  {
    id: 64,
    details: [{
      status: "cancelled"
    }]
  },
  {
    id: 74,
    details: [{
      status: "completed"
    }]
  }
];

var started_progress = arrobj.details.filter(e => ["started", "progress"].includes(e.status)).length;

var completed = arrobj.details.every(i => i.status === "completed").length;

var cancelled = arrobj.details.every(i => i.status === "cancelled").length;

预期输出

started_progress = 3
completed = 2
cancelled = 1
JavaScript ReactJS Arrays 循环 对象

评论

0赞 Pointy 6/18/2023
你想要,而不是。.filter().every()
0赞 James 6/18/2023
Array.every 不会返回具有有意义的长度的内容,它返回 true 或 false。
0赞 David Thomas 6/18/2023
我已将您发布的代码格式化为运行片段(以便可以在问题中查看),请注意,您发布的代码会产生类型错误:如果这代表您当前的结果,那很好,但如果不是,请您编辑代码,使其准确到您自己的问题?arrobj.details is undefined

答:

0赞 James 6/18/2023 #1

下面有一种将数组简化为包含各种计数的对象的方法。如果逻辑不太正确,您可能需要调整大块。if

var arrobj =[
  {id: 22, details: 
    [
     {status: "started"},
     {status: "cancelled"}
    ]
  },
  {id: 24, details: 
    [
     {status: "completed"},
     {status: "cancelled"}
    ]
  },
  { id: 44, details: 
    [
     {status: "progress"}
    ]
  },
  { id: 54, details: 
    [
     {status: "progress"},
     {status: "completed"}
    ]
  },
   { id: 64, details: 
    [
     {status: "cancelled"}
    ]
  },
   { id: 74, details: 
    [
     {status: "completed"}
    ]
  }
]

const output = arrobj.reduce((acc, el) => {
  if (el.details.length === 1 && el.details[0].status === "cancelled") {
    // only contains "cancelled"
    acc.cancelled++;
  } else if (el.details.length === 1 && el.details[0].status === "completed") {
    // only contains "completed"
    acc.completed++;
  } else if (el.details.length === 2 && el.details.find(d => d.status === "cancelled") && el.details.find(d => d.status === "completed")) {
    // only contains "completed" and "cancelled"
    acc.completed++;
  } else if (el.details.find(d => d.status === "progress" || d.status === "started")) {
    // contains "progress" or "started"
    acc.started_progress++;
  }
  return acc;
}, {
  started_progress: 0,
  completed: 0,
  cancelled: 0
});

console.log(output);