JSON在JavaScript中过滤数组

时间:2012-04-21 13:27:08

标签: javascript arrays json parsing

我有这个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]"

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

<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>