You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅遍历JSON数组中的对象,排除字符串元素?

过滤JSON数组中的对象元素

我有一个混合了对象和字符串元素的JSON数组,遍历的时候因为字符串存在导致循环失败,只想遍历其中的对象元素。之前试了几种判断方法都没用:

  • 使用if(json.length!=3):遇到对象时因为无法获取length属性失败
  • 使用json.hasOwnProperty("field_id"):遇到字符串"and"时失败
  • 使用if(json.length=undefined):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
    }
]

解决方案

你可以通过判断元素类型来筛选对象,这里有几个实用的方法:

方法1:先判断元素是否为对象

遍历数组时,先检查元素是不是对象(还要排除null,因为typeof null会返回"object"),如果是再处理:

const data = [/* 你的JSON数组 */];
for (const item of data) {
    if (typeof item === 'object' && item !== null && !(item instanceof Array)) {
        // 这里处理对象元素,比如打印field_id
        console.log(item.field_id);
    }
}

方法2:结合属性判断

如果确定只有目标对象有field_id属性,可以先确认是对象,再检查这个属性是否存在:

const data = [/* 你的JSON数组 */];
data.forEach(item => {
    if (typeof item === 'object' && item !== null && item.hasOwnProperty('field_id')) {
        // 处理对象元素
        console.log(item);
    }
});

方法3:先过滤再遍历

先把数组里的对象元素单独过滤出来,再遍历处理,代码更清爽:

const data = [/* 你的JSON数组 */];
const objectsOnly = data.filter(item => typeof item === 'object' && item !== null && !(item instanceof Array));
objectsOnly.forEach(obj => {
    // 处理每个对象
    console.log(obj.operator_id);
});

内容的提问来源于stack exchange,提问作者Kay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:40:47