簡體   English   中英

比較和減少復雜的對象數組

[英]Compare and reduce complex array of objects

我有一個``數據集,它是數據庫中某些項目的對象數組,其中包含特定項目的estimatedDays日期需要多長時間的詳細信息:

items : [
    {
    id: '1'
    shippingMethods: [
        {
        id: 'STANDARD',
        estimatedDays: 3,
        },
        {
        id: 'TWODAY',
        estimatedDays: 2,
        },
        {
        id: 'NEXTDAY',
        estimatedDays: 1,
        },
    ]
    },
    {
    id: '2'
    // same shipping data as above but standard shipping will take 4 estimatedDays
    },
    {
    id: '3'
    // same shipping data as above but TWODAY shipping will take 3 estimatedDays
    },
]

我想知道是否有一個reduce函數可以比較每個item中的每個shippingMethod.id並返回一個新數組,只返回shippingMethod.estimatedDays與所有項目相比最大的數據。

因此,結束數組將是一個對象數組(在這種情況下)有3種運送方式:STANDARD,TWODAY和NEXTDAY。

在這里你使用reduce方法,

降低

 var items = [ { id: '1', shippingMethods: [ { id: 'STANDARD', estimatedDays: 3 }, { id: 'TWODAY', estimatedDays: 2 }, { id: 'NEXTDAY', estimatedDays: 1 }, ] }, { id: '2', shippingMethods: [ { id: 'STANDARD', estimatedDays: 4 }, { id: 'TWODAY', estimatedDays: 2 }, { id: 'NEXTDAY', estimatedDays: 1 }, ] }, { id: '3', shippingMethods: [ { id: 'STANDARD', estimatedDays: 3 }, { id: 'TWODAY', estimatedDays: 3 }, { id: 'NEXTDAY', estimatedDays: 1 }, ] }, ]; var outItems = items.reduce(function(accu, curr){ if(curr.shippingMethods) { if(accu.length > 0) { for(var i = 0; i < curr.shippingMethods.length; i++) { var current = curr.shippingMethods[i]; if(accu[i].id === current.id && accu[i].estimatedDays < current.estimatedDays) { accu[i] = current; } } } else { accu = curr.shippingMethods; } } return accu; }, []); console.log(outItems); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM