【问题标题】:Compare and reduce complex array of objects比较和减少复杂的对象数组
【发布时间】:2017-08-22 07:02:52
【问题描述】:

我有一个``数据集,它是一个对象数组,用于数据库中的某些项目,其中包含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 函数可以比较每个项目中的每个 shippingMethod.id 并仅在 shippingMethod.estimatedDays 与所有项目相比最大时返回一个新数组。

因此,最终数组将是一个对象数组,具有(在这种情况下)3 种运输方式:STANDARD、TWODAY 和 NEXTDAY。

【问题讨论】:

  • 你可以查看我下面的答案

标签: javascript arrays node.js ecmascript-6 reduce


【解决方案1】:

您可以使用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);

【讨论】:

  • 谢谢你。您认为有没有更优化的方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2013-04-09
  • 2017-08-17
相关资源
最近更新 更多