如何在react

时间:2019-05-23 06:12:14

标签: javascript reactjs

我有一个类组件,其状态包含一个filterItems []空白数组。我需要在filterItems数组中填充值

所以,我有一个来自API的数据,看起来像这样:

0:
emp_code: "a001"
company_code: "company_a"
keys: ["id", "post" ] 
dtypes: ["str", "int"]

1:
emp_code: "b001"
company_code: "company_b"
keys: ["sal", "name" ] 
dtypes: ["int", "str"]

//so on for other companies and employees

如此,我有几个员工。 现在,我必须遍历此api数据并提取信息,并将其存储到另一个名为“过滤器”的数组中,并将其传递给函数。

我的过滤器数组应如下所示:

filters: [
        {
          key_name: "id",
          company_code: "company_a",
          input_type: "text",
          dtype: "str"
        },
        {
          key_name: "post",
          company_code: "company_a",
          input_type: "text",
          dtype: "int"
        },
//... keys for other company
]

基本上, 我需要在react中执行以下操作

for each emp_code
  for each company_code
     for each key:
         keys[i]== filters.key_name
         company_code== filters.company_code
//...so on

这里的问题是,每个公司都有一组键,因此,如果员工属于同一公司,那么我就不需要再次添加到过滤器数组中。 因此,我基本上需要检查唯一的company_code并将公司必须拥有的不同类型的键添加到过滤器数组中。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您想要这样过滤数据:

假设您将API数据存储在名为myArr的变量中

创建一个名为updatedArr的新变量,该变量将映射到myArr

const updatedArr = myArr.map((company, compIndex, compArr) => {
    return company.keys.map((key, keyIndex, keyArr) => {
        return {
            key_name: key,
            company_code: company.company_code,
            input_type: "text",
            dtype: company.dtypes[keyIndex]
        }
    })
}).reduce((acc, cur) => {
    return [...acc, ...cur]
}, [])

然后解析updatedArr以仅获取唯一值

let uniqueValues = [];
//parses out duplicates
updatedArr.forEach(function(item) {
  //i will be 0 or more if there already is an item in our array, which means the current item we are iterating over is a duplicate
  var i = uniqueValues.findIndex(
    x => x.dtype == item.dtype && x.company_code == item.company_code
  );
  if (i <= -1) {
    //if item is not yet inside uniqueValues, add it to uniueValues
    uniqueValues.push(item);
  }
});

然后使用uniqueValues更新您的componentState

this.setState({
   filters: uniqueValues
})

还创建了一个沙箱来向您展示此工作中的实际情况: https://codesandbox.io/s/rendering-companies-ibs7g

答案 1 :(得分:0)

假设您的数据是一个数组。

    let filters = [];

    data.forEach(item => {
        item.keys.forEach(key => {
            item.dtypes.forEach(dtype => {
                const filter = {
                    key_name: key,
                    company_code: item.company_code,
                    input_type: "text",
                    dtype: dtype
                };
                filters.push(filter)
            })
        })
    });