【问题标题】:JSON to filtered Array in JavaScriptJSON到JavaScript中的过滤数组
【发布时间】:2012-04-21 13:27:07
【问题描述】:

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

非常感谢任何帮助。

【问题讨论】:

  • 您必须在处理之前对其进行解析。然后,您可以遍历数组并将主键添加到集合中。如果您以前见过密钥,请忽略该项目。

标签: javascript arrays json parsing


【解决方案1】:
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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • 也许你应该使用(!cache.hasOwnPropery(pk)) 而不是(!cache.pk)
    • 非常感谢,非常有帮助,给了我一个想法。现在把它翻译成 JScript,应该不会太难。
    【解决方案3】:
    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多