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