【问题标题】:How to fetch values from object containing array objects?如何从包含数组对象的对象中获取值?
【发布时间】:2021-02-07 17:49:32
【问题描述】:

我有一个如下所示的对象。它可以有任意数量的Array object,每个代表ErrorType的数量。

data = 
{
  "1": [
    {
      "ErrorType": "Error-1A",
      "Error": "Wrong Password for 1A"
    },
    {
      "ErrorType": "Error-1B",
      "Error": "Host not matching"
    }
  ],
  "2": [
    {
      "ErrorType": "Error-2A",
      "Error": "Wrong User for 1A"
    },
    {
      "ErrorType": "Error-2B",
      "Error": "connectivity issue"
    }
  ],
  "3": [
    {
      "ErrorType": "Error-3A",
      "Error": "Wrong version"
    }
  ],
  "16": [
    {
      "ErrorType": "Error-4A",
      "Error": "Unknown"
    }
  ]
  ...
  ... 
}

我想捕获所有计数值并将它们按降序推入数组countArray

countArray = [16, 3, 2, 2, 1, 1];

我想捕获对应的ErrorType并将它们推送到数组errorTypeArray中。

errorTypeArray = ['Error-4A', 'Error-3A', 'Error-2B', 'Error-2A', 'Error-1B', 'Error-1A'];

到目前为止,我已经编写了以下代码,但并不完整:

const countArray = [];
const count = Object.keys(data).length;
for ( let i = 0; i < count; i++) {
    countArray.push(data[i]);
}

【问题讨论】:

    标签: javascript arrays collections


    【解决方案1】:

    如果您不需要将键与 ErrorType 匹配,那么这将起作用:

    const data = { "1": [ { "ErrorType": "Error-1A", "Error": "Wrong Password for 1A" }, { "ErrorType": "Error-1B", "Error": "Host not matching" } ], "2": [ { "ErrorType": "Error-2A", "Error": "Wrong User for 1A" }, { "ErrorType": "Error-2B", "Error": "connectivity issue" } ], "3": [ { "ErrorType": "Error-3A", "Error": "Wrong version" } ], "16": [ { "ErrorType": "Error-4A", "Error": "Unknown" } ] };
    
    let errorArray = [];
    const countArray = Object.keys(data).reduce((acc, key) => { // run over the keys
        data[key].forEach(item => {
          errorArray.push(item.ErrorType); // save the errortype
          acc.push(key); // save the key as many times as there are items in the array
        });
        return acc;
      }, [])
      .sort((a, b) => b - a);
    errorArray.reverse()
    console.log(countArray)
    console.log(errorArray)

    【讨论】:

      【解决方案2】:

      您可以使用for...of 创建一个包含计数和错误类型的对象数组,然后按以下方式对数组进行排序:

      var data = 
      {
        "1": [
          {
            "ErrorType": "Error-1A",
            "Error": "Wrong Password for 1A"
          },
          {
            "ErrorType": "Error-1B",
            "Error": "Host not matching"
          }
        ],
        "2": [
          {
            "ErrorType": "Error-2A",
            "Error": "Wrong User for 1A"
          },
          {
            "ErrorType": "Error-2B",
            "Error": "connectivity issue"
          }
        ],
        "3": [
          {
            "ErrorType": "Error-3A",
            "Error": "Wrong version"
          }
        ],
        "16": [
          {
            "ErrorType": "Error-4A",
            "Error": "Unknown"
          }
        ]
      }
      var countAndErrorTypeArray = [];
      for (const [key, value] of Object.entries(data)) {
         for ( let i = 0; i < value.length; i++) {
            var obj = {};
            obj.Count = key;
            obj.ErrorType = value[i].ErrorType
            countAndErrorTypeArray.push(obj);
         }
      }
      countAndErrorTypeArray.sort((a,b) => b.Count - a.Count);
      console.log(countAndErrorTypeArray);
      
      //you can still have the count and error type from the resulted array seperately
      var countArray = countAndErrorTypeArray.map(i => +i.Count);
      console.log(countArray);
      
      var errorTypeArray = countAndErrorTypeArray.map(i => i.ErrorType);
      console.log(errorTypeArray);

      【讨论】:

        【解决方案3】:

        简单的一个是:对键进行排序并循环以从中提取数据。

        const data = {
          "1": [{
              "ErrorType": "Error-1A",
              "Error": "Wrong Password for 1A"
            },
            {
              "ErrorType": "Error-1B",
              "Error": "Host not matching"
            }
          ],
          "2": [{
              "ErrorType": "Error-2A",
              "Error": "Wrong User for 1A"
            },
            {
              "ErrorType": "Error-2B",
              "Error": "connectivity issue"
            }
          ],
          "3": [{
            "ErrorType": "Error-3A",
            "Error": "Wrong version"
          }],
          "16": [{
            "ErrorType": "Error-4A",
            "Error": "Unknown"
          }]
        }
        
        const error = []
        const ct = []
        // Sort the key
        // Loop over and extract data
        // Now loop over the data
        Object.keys(data).sort((a, b) => b - a).forEach(key => {
          const t = data[key]
          for (let i = 0; i < t.length; i++) {
            ct.push(key)
            error.push(t[i].ErrorType)
          }
        })
        console.log(error, ct)

        【讨论】:

        • 这不是 OP 想要的。再看看
        【解决方案4】:

        我会将map 分成包含相同长度键和错误值的对,然后对键的整数值进行排序。

        一旦你有了这个成对结构,你就可以使用带有mapflatMap的数组旋转模式将其拆分为所需的结果。

        const data = {"1": [{"ErrorType": "Error-1A","Error": "Wrong Password for 1A"},{"ErrorType": "Error-1B","Error": "Host not matching"}],"2": [{"ErrorType": "Error-2A","Error": "Wrong User for 1A"},{"ErrorType": "Error-2B","Error": "connectivity issue"}],"3": [{"ErrorType": "Error-3A","Error": "Wrong version"}],"16": [{"ErrorType": "Error-4A","Error": "Unknown"}]};
        
        const errs = Object.entries(data).map(([k, v]) => 
            [v.map(() => +k), v.map(e => e.ErrorType).reverse()]
          )
          .sort((a, b) => b[0][0] - a[0][0])
        ;
        const [counts, errorTypes] = (errs[0] || [])
          .map((_, i) => errs.flatMap((_, j) => errs[j][i]))
        ;
        console.log(counts, errorTypes);

        【讨论】:

        • 嘿,深夜,所以你可能是对的,可能有一个更简单的解决方案,但我现在没有看到任何明显的东西......
        • 所以我相信我fixed it
        • @ggorlen 上面的代码抛出2个错误:-TS2339: Property 'map' does not exist on type 'unknown'.TS2339: Property 'flatMap' does not exist on type 'any[][]'.
        • 我假设您的数据不会有基于提供的结构的空数组(也没有提到 TS)。添加(errs[0] || []) 应该可以解决unknown 问题。 flatMap 可能在您的 TS 版本中不可用,但您可以将其替换为 map(...).flat(),如果也不可用,则始终有 [].concat(...map(...))
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 2014-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多