简体   繁体   English

比较和减少复杂的对象数组

[英]Compare and reduce complex array of objects

I have a ``dataset which is an array of objects for some items in a database that has the details of how long it will take in estimatedDays for a specific item to be shipped: 我有一个``数据集,它是数据库中某些项目的对象数组,其中包含特定项目的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
    },
]

I am wondering if there is a reduce function that could compare each shippingMethod.id in each item and return a new array back only where shippingMethod.estimatedDays is greatest compared to all items. 我想知道是否有一个reduce函数可以比较每个item中的每个shippingMethod.id并返回一个新数组,只返回shippingMethod.estimatedDays与所有项目相比最大的数据。

So the end array would be an array of objects with (in this case) 3 shipping methods: STANDARD, TWODAY, and NEXTDAY. 因此,结束数组将是一个对象数组(在这种情况下)有3种运送方式:STANDARD,TWODAY和NEXTDAY。

Here you go with the reduce method, 在这里你使用reduce方法,

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