[英]how to filter arrays inside an object and return the array with the most items inside?
我正在开发一个应用程序,通过 API 调用从第三方来源请求数据。 我的一个相关数据位于 object 中的 arrays。
这里的技巧是,在我进行的一些调用中,我为获取 object 包含单个数组的数据而在其他调用中,它包含多个 arrays。
我需要里面项目最多的数组的数据。
在大多数情况下,object 内部包含 2 个 arrays - 在这种情况下,我的代码运行良好,并且我可以在大多数情况下过滤我的相关数组,它是第二个数组 - 数组 [1]。
但是当 object 内部包含一个数组时 - 这就是我努力获取数据的地方。
(arrays 名称是我得到的每个 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
迭代列表/数组
reduce
one 还可以免费获得一些默认行为......
如果数组只有一个元素(无论位置如何)且未提供 initialValue,或者提供了 initialValue 但数组为空,则将返回 solo 值而不调用 callbackFn。
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; }
var object = {
"154987": [1, 2, 3],
"754896": [1, 2],
"265489": [5, 4, 3, 2, 1, 2, 4, 5]
}
var keys = Object.keys(object);
var highestArray = [];
for (var i = 0; i < keys.length; i++) {
var obj = object[keys[i]];
if (Array.isArray(obj) && obj.length > highestArray.length)
highestArray = obj;
}
console.log(highestArray);
从您的 object 中获取所有属性名称。然后遍历它以找到其中项目数最多的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.