繁体   English   中英

将 object 数组缩减为单个 object

[英]Reduce object array into single object

我有一组对象,表示某些进程随时间的运行状态。

[
  { process: 'first' , running:true},  // starting 'first' 
  { process: 'second', running:true},  // starting 'second'
  { process: 'first' , running:true},  // starting 'first' again
  { process: 'second', running:false}, // stopping 'second'
  { process: 'first' , running:false}  // stopping 'first' ( there is one more running which is not yet stopped)
]

我想按进程对这个数组进行分组并提供当前的运行状态。 预期 output,

   {
     'first' : true, // started two times but stopped only once. So there one more running
     'second' : false // started and stopped once 
   }

我所做的是将这个 object 数组分组到一个 object 中,例如,

  {
     'first': [true,true,false],
     'second': [true,false]
  }

代码,

  arr.reduce((acc, item) => {
        const key = item.process;
        if (!acc[key]) acc[key] = [];
        acc[key].push(item.running);
        return acc;
     }, {});

现在有什么优雅的方法可以从这个 state 实现我的目标吗?

您可以计算运行标志并获得 boolean 值的结果。

 const data = [{ process: 'first', running: true }, { process: 'second', running: true }, { process: 'first', running: true }, { process: 'second', running: false }, { process: 'first', running: false }], result = Object.fromEntries(Object.entries(data.reduce((r, { process, running }) => { r[process]??= 0; r[process] += running || -1; return r; }, {})).map(([k, v]) => [k, ;.v]) ); console.log(result);

我会做一个 go。 一个用于计数标志的变量(真+1,假-1)和一个响应。

arr.reduce((acc, item, index) => {
        const key = item.process;
        if (!acc.flag) //used to remove those properties easily later.
          acc.flag = {}
        if (!acc[key]) {
             acc.flag[`${key}_count`] = 0
             acc[key] = false;
        }
        acc.flag[`${key}_count`] += item.running ? 1 : -1;
        acc[key] = !!acc.flag[`${key}_count`];

        if(index === arr.length -1) // last iteration
          delete acc.flag

        return acc;
     }, {});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM