【问题标题】:How to write forEach function for JSON data in javascript如何在javascript中为JSON数据编写forEach函数
【发布时间】:2021-04-22 05:16:39
【问题描述】:

我想编写一个 forEach 函数来查找我的 JSON 中的数据 案例:

 [[{ {"Plan-Name = "qwe" , "plan_data" = "10"}
          {"Plan-Name = "asd" , "plan_data" = "10"}
          {"Plan-Name = "wrt" , "plan_data" = "10"}
      }]]

我想搜索 wrt 并打印它的 plan_data 我有一个 Current plan = wrt,所以如果当前计划与 Plan_name 匹配,则打印它的 Plan_data 我为我目前的计划 responseJson[0][0]['cuurent_plan'] 而对于 Plan_name responseJson[2]

【问题讨论】:

  • 这似乎不是有效的 json - stackoverflow.com/help/minimal-reproducible-example
  • @Shru_v,你的预期输出是什么?
  • 我从 API 中获取 JSON,它位于嵌套数组中,所以第一部分我的详细信息有当前计划:HTIL9 在同一个 API 中有特定的 Plan_name 和 Plan_data,大约有 50 个计划,所以我想做的是,如果我当前的计划是 - HTIL9,那么我想从索引 [2] 中找到 HTIL9 的计划详细信息

标签: javascript arrays json react-native


【解决方案1】:

看起来 JSON 是无效的,如果它是有效的 JSON,那么您可以按照以下方式获得所需的结果。

const getPlanData = (planData, planName: string) => {
  const planInfo = planData.find((plan) => plan["Plan-Name"] === planName);

  return planInfo;
}

const apIResponse = [[

  { "Plan-Name": "qwe", "plan_data": "11" },
  { "Plan-Name": "asd", "plan_data": "22" },
  { "Plan-Name": "wrt", "plan_data": "33" }

]
]
const planValue = getPlanData(apIResponse[0], 'wrt')
console.log('res', planValue);

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 2021-09-08
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多