如何在基于属性的javascript数组中拼接?

时间:2017-12-26 23:03:37

标签: javascript jquery angularjs

我在Angularjs Grid中获取了一组数据,我需要删除所有具有相同CustCountry的行

ex - 我的客户数组看起来像

  Customer[0]={ CustId:101 ,CustName:"John",CustCountry:"NewZealand" };
  Customer[1]={ CustId:102 ,CustName:"Mike",CustCountry:"Australia" };
  Customer[2]={ CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" };
  Customer[3]={ CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" };

因此,在网格中,如果CustomerCountry是NewZealand

,我需要删除所有三条记录

我正在使用拼接方法,让我知道如何通过CustomerCountry拼接来使用

 $scope.remove=function(CustCountry)
{
    $scope.Customer.splice(index,1);
 }

2 个答案:

答案 0 :(得分:2)

如果您对收回副本没问题,这是.filter的完美用例:

Customer = [
  { CustId:101 ,CustName:"John",CustCountry:"NewZealand" },
  { CustId:102 ,CustName:"Mike",CustCountry:"Australia" },
  { CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" },
  { CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" },
]

console.log(Customer.filter(cust => cust.CustCountry !== "NewZealand"));

答案 1 :(得分:0)

如果您考虑到某个特定国家/地区,请使用.filter()

$scope.Customer = $scope.Customer.filter(obj => obj.CustCountry !== "SpecificCountry")

如果您要删除所有包含重复国家/地区的对象,请参阅Remove duplicate values from JS array,这是您可以执行的操作:

var removeDuplicateCountries = function(arr){
    var dupStore = {};

    for (var x= 0; x < arr.length; x++){
        if (arr[x].CustCountry in dupStore){
            dupStore[arr[x].CustCountry] = false;
        } else {
            dupStore[arr[x].CustCountry] = true;
        }
    }


    var newarr = [];
    for (var x= 0; x < arr.length; x++){
        if (dupStore[arr[x].CustCountry]){
            newarr.push(arr[x]);
        }
    }

    return arr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);

或合并.filter()方法

var removeDuplicateCountries = function(arr){
    var dupStore = {};
    var newarr = arr;

    for (var x= 0; x < arr.length; x++){
        if (arr[x].CustCountry in dupStore){
            newarr = newarr.filter(obj => obj.CustCountry !== arr[x].CustCountry);
        } else {
            dupStore[arr[x].CustCountry] = true;
        }
    }

    return newarr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);

如果有许多重复的国家/地区,请使用不带.filter()

的方式