What is the recommended way to filter Objects with Unique property in the array in JS?

后端 未结 4 731
醉梦人生
醉梦人生 2021-01-29 06:53

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

4条回答
  •  一个人的身影
    2021-01-29 07:05

    You can iterate over the members and look at the KEY property. If it's not been seen before, add it to a list of seen keys and return true. If it has been seen before, return false. E.g.

    var 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",
    }]
    
    var seenKeys = Object.create(null);
    var result = array.filter(function(obj) {
      return seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true;
    });
    
    console.log(result)

    As an arrow function:

    var seenKeys = Object.create(null);
    var result = array.filter(obj => seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true);
    

提交回复
热议问题