繁体   English   中英

如何删除具有相同值的jQuery?

[英]How do I remove jQuery with the same value?

我的问题很简单,但我不能。 JSON有数据。 我正在某处进行循环推送。 但是再次添加了相同的值。 我想解决这个问题。 只有一个可以删除具有相同值的名称。

摘要;

thelist = [{"name": "test", "name": "test2", "name": "test"}]

我要删除相同的名字。 只会有一个。

控制台示例图像;

在此处输入图片说明

jQuery代码示例;

     var $el = this;
     var groupedItem = _.groupBy(itemList, function(t) { return t.unitPriceCurrency });

    $.each(groupedItem, function( key, value ) {
        var obj = JSON.stringify(value);
        var stringify = JSON.parse(obj);
        var amount = 0;
        var tax = 0;

        for (var i = 0; i < stringify.length; i++) {
            amount += stringify[i]['unitPrice'] * stringify[i]['quantity'];
            tax += stringify[i]['unitPrice'] * stringify[i]['quantity'] * stringify[i]['taxRate'] / 100;
        }

        var totalAmount = Math.round(amount * 100) / 100;
        var withTaxTotal = totalAmount + tax;

        for(let i = 0; i < totalLayout.length; i++) {                                
            totalLayout =  $.grep(totalLayout, function(value) {
                return totalLayout[i]["name"] != value.name;
            });
        }

        totalLayout.push(
            {"name": key + ' Amount'},
            {"name": key + ' Tax'},
            {"name": key + ' Total Amount'}
        );

        $el.model.set(key + ' Amount', totalAmount);
        $el.model.set(key + ' Tax', Math.round(tax * 100) / 100);
        $el.model.set(key + ' Total Amount', withTaxTotal);
    });

这是尝试使用filterfindIndex

  thelist = [{"name": "test"}, {"name": "test2"}, {"name": "test"}] Array.prototype.distinctBy= function(key){ return this.filter((value, index, self)=> { return self.findIndex((v, i)=> v[key] === value[key]) === index }); } console.log(thelist.distinctBy("name")) 

根据您的图像,对象应如下所示

thelist = [{"name": "test"}, {"name": "test2"}, {"name": "test"}]

您可以使用过滤器来达到所需的结果

thelist = thelist.filter(
            (item, index, self) =>
                index ===
                self.findIndex(t =>
                    Object.keys(thelist[0]).every(prop => t[prop] === item[prop])
                )
        );

暂无
暂无

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

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