如何以逗号分隔获取具有相同键值的对象 [英] How to get objects with same key values with comma separated

查看:68
本文介绍了如何以逗号分隔获取具有相同键值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,每个对象都有键和值.我想如果对象具有相同的键,那么它们的值应以逗号分隔所有相同键的值. 我的html代码:

I have an array of objects , each object have key and value .I want if object have same keys then their values shoud be comma sepated of all the values of same key. my html code:

<p ng-repeat="item in allOptions" class="item" id="{{item.id}}">
  {{item.id}} <input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" >  {{item}} Selected: {{bool}} 
  </p>

我的控制器代码是:

 $scope.allOptions = [
    {
      "id": "1",
      "data": "one",
    },
    {
      "id": "1",
      "data": "two",
    },
    {
      "id": "2",
      "data": "three",
    },
  ];

  $scope.data = [

  ];

  $scope.sync = function(bool, item){

    if(bool){
      // add item
      $scope.data.push(item);
    } else {
      // remove item
      for(var i=0 ; i < $scope.data.length; i++) {
        if($scope.data[i] == item.id){
          $scope.data.splice(i,1);
        }
      }      
    }
  };

在数据数组中我有对象,如果我们选择对象的相同键(相同的id值),那么我想要

In data array i have objects ,if we select same key of objects (same id value )then i want

{
          "id": "1",
          "data": "one","two",
        }

推荐答案

var myData = [{
      "id": "1",
      "data": "one",
    },{
      "id": "1",
      "data": "two",
    },{
      "id": "2",
      "data": "three",
    }];

var output = [];

//Iterating each element of the myData
myData.forEach(o => {

  //Checking the duplicate value and updating the data field
  let temp = output.find(x => { 
      if (x && x.id === o.id) {
        x.data += ", " + o.data;
        return true;
    }
  });
  if(!temp)
     output.push(o);
     
});
console.log(output);

这篇关于如何以逗号分隔获取具有相同键值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆