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

如何在JavaScript中从复杂JSON提取值并筛选不符合条件的父键

实现JSON对象的状态检查与父键记录

核心思路

遍历JSON对象的所有顶层键,检查每个子对象的importStatus字段,若其值不等于"success",则将对应的顶层键存入结果数组。

代码实现(基础版)

先假设你已经将JSON数据解析为JavaScript对象(如果是从文件读取,后面会补充方法):

// 你的JSON数据解析后的对象
const testData = {
  "Test1": {
    "protocolName": "Test1",
    "createdAsProtocolName": "AnalyticsTest1",
    "message": "Protocol already exists!",
    "importStatus": "success",
    "protocolApplicationName": "Flexi-Protocol",
    "protocolId": 1,
    "applicationId": 5
  },
  "Test2": {
    "protocolName": "Test2",
    "createdAsProtocolName": "AnalyticsTest2",
    "message": "Protocol already exists!",
    "importStatus": "success",
    "protocolApplicationName": "Flexi-Protocol",
    "protocolId": 2,
    "applicationId": 5
  },
  "Test3": {
    "protocolName": "Test3",
    "createdAsProtocolName": "AnalyticsTest3",
    "message": "Error",
    "importStatus": "failed",
    "protocolApplicationName": "Flexi-Protocol",
    "protocolId": 3,
    "applicationId": 5
  },
  "Test4": {
    "protocolName": "Test4",
    "createdAsProtocolName": "AnalyticsTest4",
    "message": "Error",
    "importStatus": "failed",
    "protocolApplicationName": "Flexi-Protocol",
    "protocolId": 4,
    "applicationId": 5
  }
};

// 初始化空数组存储结果
const failedTests = [];

// 获取所有顶层键(Test1、Test2等)
const testKeys = Object.keys(testData);

// 遍历每个键,检查状态
testKeys.forEach(key => {
  const currentStatus = testData[key].importStatus;
  // 若状态不是success,则记录父键
  if (currentStatus !== "success") {
    failedTests.push(key);
  }
});

console.log(failedTests); // 输出: ["Test3", "Test4"]

另一种遍历方式:for...in循环

如果你对forEach不太熟悉,也可以用更基础的for...in循环,逻辑完全一致:

const failedTests = [];

for (const key in testData) {
  // 可选:确保只遍历对象自身的属性,避免原型链干扰
  if (testData.hasOwnProperty(key)) {
    const currentStatus = testData[key].importStatus;
    if (currentStatus !== "success") {
      failedTests.push(key);
    }
  }
}

console.log(failedTests);

从JSON文件读取并处理(Node.js环境)

如果你的JSON数据存在本地文件中,可以用Node.js的fs模块读取并解析:

const fs = require('fs');

// 读取JSON文件
fs.readFile('./your-test-data.json', 'utf8', (err, rawData) => {
  if (err) {
    console.error('读取文件失败:', err);
    return;
  }
  
  // 将JSON字符串解析为JavaScript对象
  const testData = JSON.parse(rawData);
  
  // 执行状态检查逻辑
  const failedTests = [];
  Object.keys(testData).forEach(key => {
    if (testData[key].importStatus !== "success") {
      failedTests.push(key);
    }
  });
  
  console.log('导入失败的测试项:', failedTests);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:20:16