在JS的数组中,建议使用唯一属性过滤对象的方法是什么? [英] What is the recommended way to filter Objects with Unique property in the array in JS?

查看:175
本文介绍了在JS的数组中,建议使用唯一属性过滤对象的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据唯一属性过滤数组中的对象 在这里,我有一个数组,其中KEY是对象中的键值. 如何过滤键值唯一的对象.在对象中重复键值,但只应滤除第一个键值.

How to filter objects in array based on unique property here i have an array where KEY is the key value in the objects. How to filter the objects where key value is unique. Key value is repeated in the objects but should only the first one should be filtered out.

var array = [];
array = [
  {
    "KEY": "00001",
    "ID": "1234",
    "ID_DESC": "1234",
    "NOT_UNIQUE_VALUE": "119.0",
    "NOT_UNIQUE_TYPE": "this is not unique"
  }, 
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"11019.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  }]

结果:

uniquearray = [
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"119.0",
    "NO T_UNIQUE_TYPE":"this is not unique"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  }]

推荐答案

var uniqueArray = []
for (var i = 0; i < array.length; i++) {
    var uniquevalue = array[i];
    unique[array.KEY] = uniquevalue;
}
for (var name in unique) {
    var uniqueObject = unique[name];
    uniqueArray.push(uniqueObject);
}

这篇关于在JS的数组中,建议使用唯一属性过滤对象的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆