如何从JSONArray删除重复项

时间:2018-10-15 11:52:52

标签: javascript set

我有一个如下所示的数组:

{
    "instances":[
    {
      "Instances":"1",
      "riskdesc":"Low",
      "alert":"X-Content-Type-Options Header Missing",
      "OtherInformation":"T",
      "Method":"GET"
    },
    {
      "Instances":"1",
      "riskdesc":"High",
      "alert":"Cookie No HttpOnly Flag",
      "OtherInformation":"T",
      "Method":"GET"
    },
    {
      "Instances":"1",
      "riskdesc":"Low",
      "alert":"X-Content-Type-Options Header Missing",
      "OtherInformation":"T",
      "Method":"GET"
    }
  ]
}

最终,我需要每个对象及其对应的Riskdesc的唯一警报值,并消除重复的警报值。

我可能会对此做错事,因此,如果有一种更简单的方法来实现最终目标,我会开放意见

请在下面找到所需的输出。

enter image description here

2 个答案:

答案 0 :(得分:0)

我能想到的最快的方法是使用key/value array,询问key是否已经存在并继续前进。 key必须是您不想重复的值,因此它是每个实例的alert的值。

这有弊吗?好吧,您将重复了 alerts 值,一次是key/value array的键,一次是其中的值。

const instances = [{
    "Instances": "1",
    "riskdesc": "Low",
    "alert": "X-Content-Type-Options Header Missing",
    "OtherInformation": "T",
    "Method": "GET"
  },
  {
    "Instances": "1",
    "riskdesc": "High",
    "alert": "Cookie No HttpOnly Flag",
    "OtherInformation": "T",
    "Method": "GET"
  },
  {
    "Instances": "1",
    "riskdesc": "Low",
    "alert": "X-Content-Type-Options Header Missing",
    "OtherInformation": "T",
    "Method": "GET"
  }
];

let non_duplicates_instances = {};
for(let i=0; i<instances.length; ++i){
  const instance = instances[i];
  if( !(instance.alert in non_duplicates_instances) ){
    non_duplicates_instances[instance.alert] = instance;
  }
}

console.log(non_duplicates_instances);

答案 1 :(得分:0)

<%= form_with(model: @model, local: true, scope: I18n.locale) do |form| %>