如何从对象数组 Javascript 中获取唯一值

时间:2023-02-11
本文介绍了如何从对象数组 Javascript 中获取唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个对象数组如下:

So I have an object array that as follows:

var array = [
    {name:"Joe", date:'2018-07-01', amt:250 },
    {name:"Mars", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Saturn", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Jupiter", date:'2018-07-01', amt:250 },
]

我想根据 nameamountdate 是否重复来过滤数据.这个甚至不过滤重复的名称.

I want to filter data depending if the name, amount and date has duplicate. This one doesn't filter even a duplicate name.

var unique = array.filter((v, i, a) =>{ return a.indexOf(v) === i});

如何根据 nameamountdate 过滤重复项?

How can I filter duplicate for this one based on name, amount and date?

推荐答案

试试这个代码,它只返回唯一的对象.

Try this code it returns unique objects only.

var data = [
{name:"Joe", date:'2018-07-01', amt:250 },
{name:"Mars", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Saturn", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Jupiter", date:'2018-07-01', amt:250 },
]
var resArr = [];
data.filter(function(item){
  var i = resArr.findIndex(x => (x.name == item.name && x.date == item.date && x.amt == item.amt));
  if(i <= -1){
        resArr.push(item);
  }
  return null;
});
console.log(resArr)

如果这不是你要找的,请告诉我.

Do tell me if this is not what you're looking for.

这篇关于如何从对象数组 Javascript 中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何从 JavaScript 数组中删除重复的对象? 下一篇:在Javascript中从数组中删除重复元素

相关文章

最新文章