如何使用Lodash分组多个

时间:2019-04-10 07:34:10

标签: javascript arrays lodash

我在数组下面

const array = [
  {
    key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
    location: { lat: '22.7196', lng: '75.8577' },
    address: { city: 'NY', country: 'USA' },
    className: 'FourthActivity',
    deviceId: '1111111111111111'
  },
  { 
    key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
    location: { lat: '22.7196', lng: '75.8577' },
    address: { city: 'NY', country: 'USA' },
    className: 'FourthActivity',
    deviceId: '222222222222222'
  },
  {
    key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
    location: { lat: '22.7196', lng: '75.8577' },
    address: { city: 'Landon', country: 'UK' },
    className: 'FourthActivity',
    deviceId: '33333333333'
 }
]

我必须通过使用对象内部的两个属性(即addressclassName)对它进行分组。如何使用loadash或javascript执行此操作?

预期输出

[{
  address: { city: 'NY', country: 'USA' }, className: 'FourthActivity',
  count: 2,
  data: [{
    deviceId: 222222222222222,
  }, {
    deviceId: 1111111111111111,
  }]
}, {
  address: { city: 'Landon', country: 'UK' }, className: 'FourthActivity',
  count: 1,
  data: [{
    deviceId: 33333333333,
  }]
}]

我已经尝试过了,但是没用

var selectedVehicle = _.filter(array, 'address')

  const selectedVehicles = _.groupBy(selectedVehicle, function(item) {
  return item.makeCode;
})

console.log(selectedVehicles)

1 个答案:

答案 0 :(得分:1)

您可以reduce到一个对象中,如果给定的地址/ className对尚不存在,则创建{ address, className, count: 0, data: [] },然后获取该对象的值:

const array = [
  {
    key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
    location: { lat: '22.7196', lng: '75.8577' },
    address: { city: 'NY', country: 'USA' },
    className: 'FourthActivity',
    deviceId: '1111111111111111'
  },
  { 
    key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
    location: { lat: '22.7196', lng: '75.8577' },
    address: { city: 'NY', country: 'USA' },
    className: 'FourthActivity',
    deviceId: '222222222222222'
  },
  {
    key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
    location: { lat: '22.7196', lng: '75.8577' },
    address: { city: 'Landon', country: 'UK' },
    className: 'FourthActivity',
    deviceId: '33333333333'
 }
]
const output = Object.values(array.reduce((a, { address, className, deviceId }) => {
  const addressClassNameStr = JSON.stringify({ address, className });
  if (!a[addressClassNameStr]) {
    a[addressClassNameStr] = { address, className, count: 0, data: [] };
  }
  a[addressClassNameStr].count++;
  a[addressClassNameStr].data.push({ deviceId });
  return a;
}, {}));
console.log(output);