JSON 到 JavaScript 中过滤的数组

JSON to filtered Array in JavaScript

本文关键字:数组 过滤 JavaScript JSON      更新时间:2023-09-26

我有这个JSON字符串:

[
   {
      "pk": "alpha",
      "item": [{
         "child": "val"
      }]
   },
   {
      "pk": "beta",
      "attr": "val",
      "attr2": [
         "child1"
      ]
   },
   {
      "pk": "alpha",
      "anotherkey": {
         "tag": "name"
      }
   }
]

我需要生成一个没有重复 PK 的过滤数组,在上面的最后一个条目中:"pk": "alpha","anotherkey": { ...应从输出数组中删除。所有这些都使用 JavaScript。我尝试使用对象 JSON.parse,但它返回许多难以过滤的键、值对,例如"key=2 value=[object Object]"

任何帮助将不胜感激。

var data = JSON.parse(jsonString);
var usedPKs = [];
var newData = [];
for (var i = 0; i < data.length; i++) {
  if (usedPKs.indexOf(data[i].pk) == -1) {
    usedPKs.push(data[i].pk);
    newData.push(data[i]);
  }
}
// newData will now contain your desired result
var contents = JSON.parse("your json string");
var cache = {},
    results = [],
    content, pk;
for(var i = 0, len = contents.length; i < len; i++){
    content = contens[i];
    pk = content.pk;
    if( !cache.hasOwnPropery(pk) ){
        results.push(content);
        cache[pk] = true;
    }
}
// restuls
<script type="text/javascript">
// Your sample data
var dataStore = [
   {
      "pk": "alpha",
      "item": [{
         "child": "val"
      }]
   },
   {
      "pk": "beta",
      "attr": "val",
      "attr2": [
         "child1"
      ]
   },
   {
      "pk": "alpha",
      "anotherkey": {
         "tag": "name"
      }
   }
];
// Helper to check if an array contains a value
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}
// temp array, used to store the values for your needle (the value of pk)
var tmp = [];
// array storing the keys of your filtered objects. 
var filteredKeys = [];
// traversing you data
for (var i=0; i < dataStore.length; i++) {
    var item = dataStore[i];
    // if there is an item with the same pk value, don't do anything and continue the loop
    if (tmp.contains(item.pk) === true) {
        continue;
    }
    // add items to both arrays
    tmp.push(item.pk);
    filteredKeys.push(i);
}
// results in keys 0 and 1
console.log(filteredKeys);
</script>