大家好,我有一个问题,我有一个这样的数组

  array 1 =[
    {title: 'yes', time: "00:01:50"},
    {title: 'yes', time: "00:02:50"},
    {title: 'yes', time: "00:01:50"},
    {title: 'no', time: "02:01:00"},
    {title: 'yes', time: "02:01:50"},
    {title: 'no', time: "10:01:50"},
];


我想按标题过滤Angular2或js中的此数组到另一个数组array2是这样的

array2 = [
   {
    title :'yes',
    count:4,
    values:[
        {title: 'yes', time: "00:01:50"},
        {title: 'yes', time: "00:02:50"},
        {title: 'yes', time: "00:01:50"},
        {title: 'yes', time: "02:01:50"},
        ]
  },
  {
    title :'no',
    count:2,
    values:[
         {title: 'no', time: "02:01:00"},
         {title: 'no', time: "10:01:50"},
        ]
  }
];


其中name is the name of repeated title in the array1count is the number of repeated object by titlevalues按标题存储所有重复的对象

所以在过滤器后我想要这样的结果

array1=[
    {title: 'yes', time: "00:01:50"},
    {title: 'no', time: "00:02:50"},
   ];




array2 = [
    {
       title :'yes',
       count:4,
       values:[
          {title: 'yes', time: "00:02:50"},
          {title: 'yes', time: "00:01:50"},
          {title: 'yes', time: "02:01:50"},
        ]
     },
     {
       title :'no',
       count:2,
       values:[
          {title: 'no', time: "10:01:50"}
        ];
    }
 ];


有关更多说明,我正在像toggl timer那样以角2形式构建网站,如您在图片javascript - 如何根据搜索条件将数组的值分配给另一个?-LMLPHP中所见,因此当我单击“播放”按钮并将其暂停时,其另一个对象的输入值为title,时间为添加到数组1,这是我的angular2代码

startPlay(name:string = "", time:string = "00:00:00") {
    this.taskInputvalue.next('');
    this.play.next(true);
    this.pause.next(false);
    this.timer.next("00:00:00");
    clearInterval(this.countup);
    //push the task to array
    if(name == "") {
    name = "Add description";
    this.tasks.push({title: name, time: time});
    } else {
    name = name;
    this.tasks.push({title: name, time: time});
    }
}


但是当我像在图片中那样重复任务名称时,结果显示在彼此下面,所以我想要的是,如果第一次键入timer value,它将显示为task 1,但是当再次重复时,它应该存储在另一个数组中,所以可以遍历它,并在单击它时显示现有li下方的值,请访问toggl timer
 明白我的意思

最佳答案

您需要解释一下您需要什么,然后,如果这不是您想要的,我会进一步为您提供帮助,因为我不明白您想要的是什么,如果不是这种情况,我将写出我所理解的需求,请发表评论。我们将解决该问题,但请在以后的帖子中更加明确。

var input = [
    {title: 'yes', time: "00:01:50"},
    {title: 'yes', time: "00:02:50"},
    {title: 'yes', time: "00:01:50"},
    {title: 'no', time: "02:01:00"},
    {title: 'yes', time: "02:01:50"},
    {title: 'no', time: "10:01:50"},
];

function getData(arr) {
  var results = {};
  var resultArr = [];
  arr.forEach(function(el) {
        if (results[el.title]){
        results[el.title].count++;
      results[el.title].values.push(el);
    }else {
        results[el.title] = {
        title: el.title,
        count: 1,
        values: [el]
      };
    }
  })
  for (o in results){
    resultArr.push(results[o]);
  }
  return resultArr;
}

var output = getData(input);

09-25 16:31
查看更多