按数组内的嵌套对象属性排序

时间:2019-10-28 19:48:37

标签: javascript lodash

我坚持要尝试以numberOfCars排名前三的制造商,并且要与cars: []相同,以numberoOfCars排名前三的制造商

audi: {
  cars: [], 
  collectionName: '',
  numberOfCars: 0
}

我可以像

一样用lodash进行第一级

_.take(_.orderBy(modelData, 'numberoOfCars', 'desc'), 3)

但是我迷失了在汽车阵列上做同样的事情。

const mock = []

for (let i = 0; i < 140; i++) {
  let manufacturerName
  let name

  if (i < 20) {
    manufacturerName = 'Audi'
    name = 'A6'
  } else if (i > 19 && i < 40) {
    manufacturerName = 'BMW'
    name = '420 GC'
  } else if (i > 19 && i < 40) {
    manufacturerName = 'Mercedes'
    name = 'AMG'
  } else if (i > 39 && i < 60) {
    manufacturerName = 'Mazda'
    name = '6'
  } else if (i > 59 && i < 80) {
    manufacturerName = 'Volvo'
    name = 'V90'
  } else if (i > 79 && i < 100) {
    manufacturerName = 'Renault'
    name = 'Model'
  } else if (i > 99 && i < 120) {
    manufacturerName = 'Lamborghini'
    name = 'Aventador'
  } else if (i > 119 && i < 140) {
    manufacturerName = 'Volkswagen'
    name = 'Golf'
  }

  mock.push({
    id: i,
    name: name,
    displayName: 'display-name ' + Math.floor(Math.random() * 10),
    manufacturer: manufacturerName,
    numberoOfCars: Math.floor(Math.random() * 100000),
  })
}

const dataModel = mock.reduce((accumulator, currentValue) => {
  const key = currentValue.manufacturer

  if (accumulator[key] === undefined) {
    accumulator[key] = {
      collectionName: '',
      numberoOfCars: 0,
      cars: []
    }
  }

  if (accumulator[key].collectionName === '') {
    accumulator[key].collectionName = currentValue.manufacturer
  }

  if (currentValue.numberoOfCars !== undefined) {
    accumulator[key].numberoOfCars += currentValue.numberoOfCars
  }

  if (currentValue.numberoOfCars !== undefined) {
    accumulator[key].cars.push({
      name: currentValue.name,
      numberOfCars: currentValue.numberoOfCars
    })
  }

  return accumulator
}, {})

console.log(dataModel)

2 个答案:

答案 0 :(得分:0)

我想应该是这样的:

const cars = Object.keys(dataModel).reduce((acc, item) => {
  const collection = dataModel[item]
  return acc.concat(collection.cars)
}, []);

const top3cars = _.take(_.orderBy(cars, 'numberOfCars', 'desc'), 3);

答案 1 :(得分:0)

遍历外部对象中的键,按与外部对象中的该键关联的汽车数量对这些键进行排序,然后选择前三个键。

然后,将每个关键点简化为一个对象,该对象将克隆与该关键点关联的值并按该值对汽车进行排序,并采用第一个3:

var filtered = _.chain(dataModel)
    .keys()
    .orderBy(k=>dataModel[k].numberOfCars, 'desc')
    .take(3)
    .reduce((coll,k)=>{
        coll[k] = _.clone(dataModel[k]);
        coll[k].cars = _.chain(coll[k].cars)
            .orderBy('numberOfCars', 'desc')
            .take(3)
            .value();
        return coll;
    }, {})
    .value();

Example on jsfiddle

VLAZ致谢this answer,以帮助您了解如何通过排序对象的值来过滤对象的项目。