代码之家  ›  专栏  ›  技术社区  ›  Woodsy

数组的json测试

  •  0
  • Woodsy  · 技术社区  · 6 年前

    我正在使用一个节点模块来返回一些数据。数据将通过以下两种方式之一返回:

    单一记录

    single = {"records[]":{"name":"record1", "notes":"abc"}}
    

    多条记录

    multiple = {"records[]":[{"name":"record1", "notes":"abc"},{"name":"record2", "notes":"xyz"}]}
    

    如果我调用以下命令,我可以从单个记录中获取值

    single['records[]'].name // returns "record1"
    

    如果有多张唱片我会这样打电话给你

    multiple['records[]'][0].name // returns "record1"
    

    当我返回一条记录,但将其视为多条记录时,就会出现问题

    single['records[]'][0].name // returns undefined
    

    现在我这样测试:

    var data = nodemodule.getRecords();
    if(data['records[]'){ //test if records are returned
        if(data['records[]'].length){ //test if 'records[]' has length
            // ... records has a length therefore multiple exist
            // ... for loop to loop through records[] and send data to function call
        } else {
            // .length was undefined therefore single records
            // single function call where I pass in records[] data
        }
    }
    

    这是测试单记录还是多记录的最佳方法,因为我受到了节点模块返回的内容的限制,还是我遗漏了一些更简单的方法?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Saif    6 年前

    你可以用 Array.isArray(obj)

    目标 要检查的对象。

    真的 如果对象是数组,则为, 是的。

    if(data['records[]']){
              if(Array.isArray(data['records[]'])){
                // console.log('multiple');
              }else{
                // console.log('single');
              }
            }
    

    https://stackoverflow.com/a/26633883/4777670 读这个,它有一些更快的方法。