[英]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.