React-遍历多个嵌套数组json对象响应,然后更新State

时间:2018-12-03 17:09:38

标签: 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));
      };

2 个答案:

答案 0 :(得分:1)

如果要从类型为Query的const password = req.body.Password; const email = req.body.Email; const salt = await bcrypt.genSalt(10); const hash = await bcrypt.hash(password, salt); 数组中查找元素的名称,则只有一个这样的元素:

Hash: $2b$10$nK1.wW71NcBIQkMQq6wpHe/HMhCjOaQNy9BpfPDef01
password: 123
version: 3.0.2

如果查询元素不止一个,则可以使用过滤器获取所有查询元素,然后循环遍历每个查询元素。

included

答案 1 :(得分:1)

如果要查找的类型只有一个元素,则可以使用find,或者如果有更多use过滤器。

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

const typeMatched = schedules.included.find( included => included.type === "Query");

console.log(': ', typeMatched);

const schedulesObj = {
  data: [
    {
      id: "2147483610",
      type: "Schedule"
    }
  ],
  included: [
    {
      id: "21468486",
      type: "Query",
      name: "Query1"
    },
    {
      id: "43573457345",
      type: "DataSource",
      name: "DataSource1"
    },
    {
      id: "21468482",
      type: "Query",
      name: "Query2"
    },
    {
      id: "21468484",
      type: "Query",
      name: "Query3"
    },
  ]
};
const typeMatchedArray = schedulesObj.included.filter( included => included.type === "Query");

console.log('Query Type List: ', typeMatchedArray)