首页 > 解决方案 > 如何过滤对象内的数组并返回其中包含最多项目的数组?

问题描述

我正在开发一个通过 API 调用从第三方来源请求数据的应用程序。我的一个相关数据位于对象内的数组中。

这里的技巧是,在某些调用中,我正在获取对象包含单个数组的数据,而在其他调用中,它包含多个数组。

我需要里面有最多项目的数组的数据。

在大多数情况下,该对象内部包含 2 个数组 - 在这种情况下,我的代码运行良好,我可以过滤我的相关数组,大多数情况下它是第二个数组 - 数组 [1]。

但是当该对象内部包含一个数组时 - 这就是我努力获取数据的地方。

(数组名称是我得到的每个 JSON 中的随机数,所以我需要一个通用的解决方案)。

这是示例

object{

 "154987" [150 items],
 "754896" [13 items],
 "265489" [11 items]

}

到目前为止,这是我的代码中的内容,它不能仅使用单个数组

   function getCurrentBsrByObjectKeyIndex(index) {
      product.bsrObjectKey = (Object.keys(asinData.products[0].salesRanks)[index]);
      product.bsrHistory = asinData.products[0].salesRanks[product.bsrObjectKey];
      product.currentBsr = product.bsrHistory[product.bsrHistory.length-1];
    }
    function correctBsrObjectKey() {
      getCurrentBsrByObjectKeyIndex(1);
      if (product.bsrHistory.length < 15){
        getCurrentBsrByObjectKeyIndex(0);
      }
    }
    correctBsrObjectKey();

标签: javascriptarraysfilteringjavascript-objects

解决方案


方法如下。

  1. 通过使用直接访问所有对象第一级数组的列表(数组)Object.values
  2. 通过迭代列表/数组Array.prototype.reduce

function getArrayOfMaximumLength(obj) {
  return Object
    .values(obj)
    .reduce((maxArr, arr) =>
      // this implementation breaks at
      // an entirely emtpy `values` array

      ((maxArr.length > arr.length) && maxArr) || arr

      // // this implementation does never break but always
      // // at least returns an empty array ... [] ...
      // // which might unwantedly shadow the consumption of
      // // broken data structures
      //
      // ((maxArr.length > arr.length) && maxArr) || arr, []
    );
}

const sample_1 = {
  "754896": ['foo', 'bar', "baz"],
  "154987": ['foo', 'bar', "baz", "biz", "buz"],
  "265489": ['foo'],
};
const sample_2 = {
  "265489": ['foo'],
  "754896": ['foo', 'bar', "baz"],
};
const sample_3 = {
  "754896": ['foo', 'bar', "baz"],
};
const invalid_sample = {};

console.log(
  'getArrayOfMaximumLength(sample_1) ...',
  getArrayOfMaximumLength(sample_1)
);
console.log(
  'getArrayOfMaximumLength(sample_2) ...',
  getArrayOfMaximumLength(sample_2)
);
console.log(
  'getArrayOfMaximumLength(sample_3) ...',
  getArrayOfMaximumLength(sample_3)
);
console.log(
  'getArrayOfMaximumLength(invalid_sample) ...',
  getArrayOfMaximumLength(invalid_sample)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }


推荐阅读