javascript - 如何过滤对象内的数组并返回其中包含最多项目的数组?
问题描述
我正在开发一个通过 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();
解决方案
方法如下。
- 通过使用直接访问所有对象第一级数组的列表(数组)
Object.values
- 通过迭代列表/数组
Array.prototype.reduce
- reducer 或回调函数总是比较两个值,第一个参数由回调之前的迭代传递作为最大长度的 back then 数组,第二个参数是当前迭代步骤的数组。
- 然后该函数比较两个数组并返回(返回到下一次迭代中)最大长度的新的或旧的(取决于比较)数组。
- 使用
reduce
一个还可以免费获得一些默认行为......如果数组只有一个元素(与位置无关)且没有提供initialValue,或者如果提供了initialValue但数组为空,则不调用callbackFn返回solo值。
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; }
推荐阅读
- maven - 如何使用来自 dockerfile 的 Maven 创建和运行 docker 镜像
- typescript - 带有 mousedown、mousemove 和 mouseup 的 Cypress .trigger 命令不起作用
- vim - 管道 ripgrep 搜索结果到 vim 并在确切的搜索位置打开文件
- c# - 如何通过 docker 使用启动配置文件运行 .net 核心应用程序
- python - 仅替换数值
- react-native - 如何将依赖项导入 React Native 项目?
- sql - 将缺少的成员从其他表 SQL Server 添加到表
- linux - 组装:系统调用被跳过
- powershell - 为什么某些脚本在锁定时无法远程
- reactjs - 使用 Jest/Enzyme 测试经过身份验证的路由