【问题标题】:Keep Masterlist of Objects in Array, check array if it exists before adding a new object在数组中保留对象的主列表,在添加新对象之前检查数组是否存在
【发布时间】:2016-07-26 04:09:04
【问题描述】:

下面的代码不能按预期工作。它从不检查主列表中的服务器。难道我做错了什么?

var servers = [];
$.serverlist.addServers = function(jsonData) {
for (var server in servers) {
    if (server["ID"] == jsonData["ID"]) {
        // server exists, dont add, just update
    } else {
        //server doesnt exist, just add it
    }
}

我收到的jsonData 格式如下:

{ "ID": 1, "something else": "Value", "another key": "Key Val" }

所以当它进入数组时,数组状态(如果有多个添加)

[
 0:
   {
    "ID":1,
    "something else": "Value",
    "another key": "Key Val"
   }
  1: 
   {
    "ID":2,etc...
   } 
]

【问题讨论】:

    标签: arrays object search


    【解决方案1】:

    尝试测试数组长度。

    if( servers.length > 0 ){
        // Server exist!
        console.log("Append!");
    }else{
        // Doesn't...
        console.log("Create the array.");
    }
    

    编辑

    对于特定的对象,应该这样做:

    if( servers.indexOf(jsonData["ID"]) != -1 ){
        // Data is in array
        console.log("It's there.");
    }else{
        // Doesn't...
        console.log("It's not there.");
    }
    



    第二次编辑

    我做了一个CodePen 它应该是什么样子。
    但我不确定您的数据...当您控制台记录它时,它看起来像 DOM 对象格式。
    我认为它与 json 或对象不同......

    我基于一组对象制作了我的示例。 查看 CodePen 控制台。

    var servers = [
      {
        "ID":1,
        "something else": "Value",
        "another key": "Key Val"
       },
      {
        "ID":2,
        "something else": "another Value",
        "another key": "another Key Val"
       },
      {
        "ID":3,
        "something else": "Boring Value",
        "another key": "Interesting!"
       },
      {
        "ID":4,
        "something else": "arrggg.",
        "another key": "Yeah!"
       } 
    ];
    
    for(i=0;i<servers.length;i++){
      var temp = servers[i];
      if (temp.ID== 3){
        console.log("Found!");
        break;                  // Exits the loop when found ID = 3
      }else{
        console.log("NOT fount yet... Still checking.");
      }
    }
    

    【讨论】:

    • 我会这样做,但我会处理服务器阵列中的很多对象,我需要找到一个具有相同 ID 的对象,因为它们都是唯一的。
    • 您应该展示您的数组的结构以获得更具体的答案... ;)
    • 接近哈哈!我想我的帖子不清楚。我收到的 jsonData 是这样格式化的。 { "ID": 1, "something else": "Value", "another key": "Key Val" } 所以当它进入数组时,数组状态[如果有多个添加] [ 0: {"ID ":1,"something else": "Value","another key": "Key Val"} 2: {"ID":2,etc...} ]
    • 最初没有看到那个按钮。已添加。
    猜你喜欢
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    相关资源
    最近更新 更多