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

后端 未结 4 726
醉梦人生
醉梦人生 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条回答
  •  -上瘾入骨i
    2021-01-29 07:01

    I would go with reduce(), collecting unique elements into a Map (it even preserves insertion order, if that is expected), and packing it back to an array at the end:

    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 result = Array.from(array.reduce((m,o) => {
      if(!m.has(o.KEY))
        m.set(o.KEY, o);
      return m;
    }, new Map()).values());
    
    console.log(result)

提交回复
热议问题