gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:26:32 25 4
gpt4 key购买 nike

我坚持这一件事,试图按 numberOfCars 排名前 3 名制造商,并且,要对 cars: [] 进行同样的操作,按 numberoOfCars 排名前 3 名

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)

最佳答案

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

然后,将每个键简化为一个对象,该对象克隆与该键关联的值并以该值对汽车进行排序并获取前 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

归功于this answer VLAZ 提供有关如何通过对象值的排序来过滤对象项目的帮助。

关于javascript - 按数组内的嵌套对象属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58597484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com