简体   繁体   English

如何根据属性拼接一个javascript数组?

[英]How to Splice in a javascript array based on property?

I am getting an array of data in Angularjs Grid and I need to delete all the rows which has same CustCountry我在 Angularjs Grid 中获取了一组数据,我需要删除所有具有相同 CustCountry 的行

ex - My Customer Array looks like 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" };

So , in the Grid I need to delete all three records if CustomerCountry is NewZealand因此,如果 CustomerCountry 是新西兰,则在网格中我需要删除所有三个记录

I am using splice method and let me know how can I use by splicing through CustomerCountry我正在使用拼接方法,让我知道如何通过 CustomerCountry 拼接使用

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

If you're okay with getting a copy back, this is a perfect use case for .filter :如果您可以取回副本,这是.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"));

if you have one specific country in mind then just use .filter()如果您有一个特定的国家/地区,那么只需使用 .filter()

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

If you want to delete all objects with duplicate countries then, referring to Remove duplicate values from JS array , this is what you can do:如果您想删除所有具有重复国家/地区的对象,请参阅从 JS 数组中删除重复值,您可以这样做:

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);

Or incorporating the .filter() method或者结合 .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);

if there are many duplicate countries then use the way without .filter()如果有很多重复的国家,那么使用没有 .filter() 的方式

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

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