I have this JSON string:

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

And I need to produce a filtered array without repeated PK, in the example above the last entry: "pk": "alpha","anotherkey": { ... should be eliminated from the output array. All this using JavaScript. I tried with the object JSON.parse but it returns many key,value pairs that are hard to filter for example "key=2 value=[object Object]".

Any help is greatly appreciated.

share|improve this question
1  
You have to parse it before processing. You can then walk through the arrays and add the primary keys to a set. If you've seen a key before, just ignore the item. – Niklas B. Apr 21 '12 at 13:30

3 Answers

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
share|improve this answer
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
share|improve this answer
Maybe you should use (!cache.hasOwnPropery(pk)) instead of (!cache.pk) – Niklas B. Apr 21 '12 at 13:37
@Niklas thanks! – wong2 Apr 21 '12 at 13:38
Thanks a lot, very helpful, gives me an idea. Now to translate this to JScript, shouldn't be too hard. – user1348340 Apr 21 '12 at 14:40
<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>
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.