javascript - React - 循环遍历多个嵌套数组json对象响应然后更新状态

标签 javascript json reactjs

我有一些具有以下形状的数据。时间表数据还附加有其他标识信息,即 schedules.included,它是一个数组的数组。我想循环遍历每个包含的数组并通过 type 元素找到它。我不完全确定如何按类型获取每个 included[] 然后分别使用每个数组中的数据更新状态。 forEach 是正确的方法吗?

const schedules = {
  data: [
    {
      id: "2147483610",
      type: "Schedule"
    }
  ],
  included: [
    {
      id: "21468486",
      type: "Query",
      name: "Query1"
    },
    {
      id: "43573457345",
      type: "DataSource",
      name: "DataSource1"
    }
  ]
};

然后我想用我需要的任何数据更新状态。

      getData = () => {
        axios({
          method: "get",
          url: `/endpoint/with/this/data`
        })
          .then(response => {
            console.log(response);
            var obj = schedules.included[i].type;
            obj.forEach(function(type) {
            alert(type.name);
            });
            this.setState({
              schedules: schedules.data,
              //update with name from type Query
            });
          })
          .catch(error => console.log(error.response));
      };

最佳答案

如果你想从 included 数组中查找 type = Query 的元素名称,并且只有一个这样的元素:

var query = schedules.included.find(el => el.type == "Query");
console.log(query.name); // output Query1

如果有多个查询元素,您可以使用过滤器来获取所有查询元素,然后循环遍历它们对每个元素执行操作。

var queries = schedules.included.filter(el => el.type == "Query");
queries.forEach(q => console.log(q.name));

关于javascript - React - 循环遍历多个嵌套数组json对象响应然后更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53598549/

相关文章:

javascript - 在 watch 破坏测试中使用 Jasmine 形式有效性进行 AngularJS 单元测试

javascript - node.js,setTimeout回调方法和 "this"

javascript - 我如何处理 jQuery.Ajax 中的时间响应(数据类型 : JSON)?

reactjs - 错误 : Unable to resolve module ./Easing from node_modules\react-native-reanimated\src\Animated.js

根据另一个变量的 JavaScript 动态变量名称

javascript - 有没有办法检查特定点 (X,Y) 是否在 SVG 元素中?

javascript - 我怎样才能按原样打印页面

json - NewtonSoft Json 反序列化错误 - 无法将字符串转换为十进制 :/Date(1490721584000-0500)/

c# - 从 JSON 字符串中提取值 c#

reactjs - REACT - 在渲染 APP 之前检查身份验证