使用 javascript 删除与对象的另一个键值对对应的对象数组中的重复项

To remove duplicate among array of objects corresponding to the other key and value pair of object using javascript

有一个对象数组,对象有两个键值对。

[{fruit:"apple",locale:"US"},
{fruit:"orange",locale:"US"},
{fruit:"banana",locale:"US"},
{fruit:"apple",locale:"US"},
{fruit:"orange",locale:"IT"},
{fruit:"apple",locale:"IT"},
{fruit:"banana",locale:"IT"},
{fruit:"orange",locale:"IT"}
{fruit:"apple",locale:"IT"}]

如何实现 水果不应该在同一地区重复, 不同地区的水果可以一样。

您可以通过匹配当前迭代的索引值来筛选对象。像这样:

var data=[{fruit:"apple",locale:"US"},{fruit:"orange",locale:"US"},{fruit:"banana",locale:"US"},{fruit:"apple",locale:"US"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"},{fruit:"banana",locale:"IT"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"}];

var result = data.filter((e,i,self)=>self.findIndex(k=>k.fruit==e.fruit && k.locale==e.locale)==i);

console.log(result);

或者您可以使用 Map:

var data=[{fruit:"apple",locale:"US"},{fruit:"orange",locale:"US"},{fruit:"banana",locale:"US"},{fruit:"apple",locale:"US"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"},{fruit:"banana",locale:"IT"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"}];

var result = [...new Map(data.map(k=>[`${k.fruit}|${k.locale}`, k])).values()];

console.log(result);
 

试试这个..

    obj = [{fruit:"apple",locale:"US"},
        {fruit:"orange",locale:"US"},
        {fruit:"banana",locale:"US"},
        {fruit:"apple",locale:"US"},
        {fruit:"orange",locale:"IT"},
        {fruit:"apple",locale:"IT"},
        {fruit:"banana",locale:"IT"},
        {fruit:"orange",locale:"IT"}
        {fruit:"apple",locale:"IT"}]

        const uniqueArray = this.obj.filter((item, index) => {
          const temp = JSON.stringify(item);
          return index === this.obj.findIndex(obj => {
          return JSON.stringify(obj) === temp;
          });
        });

        console.log(uniqueArray);