计算数组中对象中两个键的出现

时间:2018-07-03 11:12:10

标签: javascript

我具有以下带有对象的数组,并使用以下代码创建了带有键“ id”的计数:

var arr=[
{ id: 123, 
  title: "name1",
  status: "FAILED"
},
{
 id: 123,
 title: "name1", 
 status: "PASSED"
},
{
 id: 123,
 title: "name1",
 status: "PASSED"
},
{
 id: 123,
 title: "name1",
 status: "PASSED"
},
{
 id: 1234,
 title: "name2",
 status: "FAILED"
},
{
 id: 1234,
 title: "name2",
 status: "PASSED"
}

];


const test =arr.reduce((tally, item) => {
				
			  if (!tally[item.id]) {
				tally[item.id] = 1;
			  } else {
				tally[item.id] = tally[item.id] + 1;
			  }
			  return tally;
			}, {});
      
console.log(test);

现在我要做的是修改提示音,同时考虑关键状态,这样结果将是这样的:

[
{id:123, status:"PASSED", tally:3},
{id:123, status:"FAILED", tally:1},
{id:1234, status:"PASSED", tally:1},
{id:1234, status:"FAILED", tally:1}
]

有什么主意吗?谢谢!

4 个答案:

答案 0 :(得分:1)

只需输入密钥item.id + item.status,这就是一个简单的分配

const res = Object.values(arr.reduce((a, b) => {
  a[b.id + b.status] = Object.assign(b, {tally: (a[b.id + b.status] || {tally: 0}).tally + 1});
  return a;
}, {}));

console.log(res);
<script>
const arr=[
  { id: 123,
    title: "name1",
    status: "FAILED"
  },
  {
    id: 123,
    title: "name1",
    status: "PASSED"
  },
  {
    id: 123,
    title: "name1",
    status: "PASSED"
  },
  {
    id: 123,
    title: "name1",
    status: "PASSED"
  },
  {
    id: 1234,
    title: "name2",
    status: "FAILED"
  },
  {
    id: 1234,
    title: "name2",
    status: "PASSED"
  }

];
</script>

答案 1 :(得分:1)

你去哪里

const test = arr.reduce((acc, item) => {        
    let found = acc.find(obj => obj.id === item.id && obj.status === item.status)
    if (typeof found === "undefined") {
        item.tally = 1
        acc.push(item);
    } else {
        found.tally++;
    }
    return acc;
}, []);

答案 2 :(得分:0)

您应该首先使用包含ID和状态的键对项目进行分组:

const result = arr.reduce((acc, item) => {
  const key = item.id + item.status;
  acc[key] = acc[key] || { ...item, tally: 0 };
  acc[key].tally++;
  return acc;
}, {});

console.log( Object.values(result) );

输出:

[
  { id: 123, title: 'name1', status: 'FAILED', tally: 1 },
  { id: 123, title: 'name1', status: 'PASSED', tally: 3 },
  { id: 1234, title: 'name2', status: 'FAILED', tally: 1 },
  { id: 1234, title: 'name2', status: 'PASSED', tally: 1 },
]

答案 3 :(得分:0)

只需结合使用idstatus来创建密钥。并使用它制作地图。之后,您可以简单地从中获得所需的结果。 请尝试以下操作:

var arr=[{id:123,title:"name1",status:"FAILED"},{id:123,title:"name1",status:"PASSED"},{id:123,title:"name1",status:"PASSED"},{id:123,title:"name1",status:"PASSED"},{id:1234,title:"name2",status:"FAILED"},{id:1234,title:"name2",status:"PASSED"}];


const map =arr.reduce((tally, item) => {
	tally[item.id+"_"+item.status] = (tally[item.id+"_"+item.status] || 0) +1;
  return tally;
}, {});
      
const result = Object.keys(map).map((a)=>{ 
  var obj = {
      id : a.split("_")[0],
      status : a.split("_")[1],
      tally : map[a]
  };
  return obj;
});
      
console.log(result);