【问题标题】:How do i only get objects from the JSON and not the strings?我如何只从 JSON 而不是字符串中获取对象?
【发布时间】:2023-02-10 02:15:44
【问题描述】:

我有一个 JSON,我想遍历它但是当我遍历它时,由于它存在的字符串,循环失败了。我如何循环遍历 JSON 中的对象?

我只想遍历该 JSON 中的对象。

  • 我试过if(json.length!=3)但是当它碰到物体时它失败了因为我认为它找不到物体的长度
  • 我也尝试了json.hasOwnProperty("field_id"),当我点击字符串“and”时,它也失败了
  • 我也试过 if(json.length=undefined) 也失败了,因为长度本身进入了未定义状态

这是我的 JSON:

[
    {
        "field_id": 122,
        "operator_id": "1",
        "where_flag": true
    "and",
    {
        "field_id": 128,
        "operator_id": "0",
        "where_flag": true
    },
    "and",
    {
        "field_id": 148,
        "operator_id": "1",
        "where_flag": true
    }
]

【问题讨论】:

    标签: javascript json


    【解决方案1】:

    我建议先过滤项目,然后遍历对象:

    function isObject(value) {
      return typeof value === "object" && value !== null
    }
    
    array.filter(item => isObject(item)).forEach(...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 2021-10-23
      • 2012-11-26
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多