替换路径名以使用接收到的JSON响应密钥javascript获取值

ffvjumwh  于 2023-02-06  发布在  Java
关注(0)|答案(1)|浏览(74)

给出下面的json响应。

{
    "status": "success",
    "data": {
    "cheapest": {
        "data": [
      {
        "logistic_id": 1,
        "rate_id": 21
      }
    ]
    },
    "reguler": {
        "data":[
      {
        "logistic_id": 5,
        "rate_id": 74
      }
    ]
    },
    "ranked": {
        "data": []
    }
}
}

要获取logistic_id值并存储到logisticIdValue,我使用路径:

set("logisticIdValue", x.data.reguler.data[0].logistic_id)

我想使用迭代从响应中获取logistic_id值,这样我就不必编写const cheost、reguler和ranked来进行迭代。它可能涉及key语法,类似于此,但我不知道什么是正确的语法

set("logisticIdValue", x.data.key[1].data[0].logistic_id)
nnsrf1az

nnsrf1az1#

let data = {
  "status": "success",
  "data": {
    "cheapest": {
      "data": [{
        "logistic_id": 1,
        "rate_id": 21
      }]
    },
    "reguler": {
      "data": [{
        "logistic_id": 5,
        "rate_id": 74
      }]
    },
    "ranked": {
      "data": []
    }
  }
};

for (const [key, value] of Object.entries(data)) {
  if (key === 'data') {
    for (const [key1, value1] of Object.entries(value)) {
      for (const [key2, value2] of Object.entries(value1)) {
        value2 && value2.map((e, i, arr) => {
          console.log('logistic_id:', e.logistic_id);
        })
      }
    }
  }
}

相关问题