我有一个问题,从数组记录的东西。我需要从每个地方找到最高评级的位置,我需要记录这3个位置的名称和坐标。我被困在这里有一段时间了,现在有人知道怎么做吗?
这是我已经有的代码:
let locaties = [
{naam: 'locatie1', type: 'cafe', rating: 8, coordinaat: {lat: 17, lon: 3},},
{naam: 'locatie2', type: 'winkel', rating: 3, coordinaat: {lat: 23, lon: 9},},
{naam: 'locatie3', type: 'Restaurant', rating: 7, coordinaat: {lat: 3, lon: 17},},
{naam: 'locatie4', type: 'winkel', rating: 7, cordinaat: {lat: 20, lon: 10},},
{naam: 'locatie5', type: 'cafe', rating: 1, coordinaat: {lat: 12, lon: 13},},
{naam: 'locatie6', type: 'winkel', rating: 5, coordinaat: {lat: 13, lon: 2},},
{naam: 'locatie7', type: 'Restaurant', rating: 6, coordinaat: {lat: 7, lon: 17},},
{naam: 'locatie8', type: 'Restaurant', rating: 2, cordinaat: {lat: 3, lon: 15},},
{naam: 'locatie9', type: 'cafe', rating: 4, coordinaat: {lat: 30, lon: 12},},
{naam: 'locatie10', type: 'winkel', rating: 9, cordinaat: {lat: 27, lon: 19},},
];
Object.keys(locaties).forEach(key => {
console.log(key);
console.log(locaties[key].naam);
})
let locations = [{
name: 'locatie1',
type: 'cafe',
rating: 8,
coordinate: {
lat: 17,
lon: 3
},
},
{
name: 'locatie2',
type: 'winkel',
rating: 3,
coordinate: {
lat: 23,
lon: 9
},
},
{
name: 'locatie3',
type: 'Restaurant',
rating: 7,
coordinate: {
lat: 3,
lon: 17
},
},
{
name: 'locatie4',
type: 'winkel',
rating: 7,
coordinate: {
lat: 20,
lon: 10
},
},
{
name: 'locatie5',
type: 'cafe',
rating: 1,
coordinate: {
lat: 12,
lon: 13
},
},
{
name: 'locatie6',
type: 'winkel',
rating: 5,
coordinate: {
lat: 13,
lon: 2
},
},
{
name: 'locatie7',
type: 'Restaurant',
rating: 6,
coordinate: {
lat: 7,
lon: 17
},
},
{
name: 'locatie8',
type: 'Restaurant',
rating: 2,
coordinate: {
lat: 3,
lon: 15
},
},
{
name: 'locatie9',
type: 'cafe',
rating: 4,
coordinate: {
lat: 30,
lon: 12
},
},
{
name: 'locatie10',
type: 'winkel',
rating: 9,
coordinate: {
lat: 27,
lon: 19
},
},
];
highest_rated_locations = locations
.sort((a, b) => b.rating - a.rating) // order elements by rating descending. Note: the original locations array changes, since the sort method is mutable, if the original array shouldn't be changed, use Array.from
.slice(0, 3) // return the first three elements of the array
for (const location of highest_rated_locations) {
console.log(`Name: ${location.name} | Lattitude: ${location.coordinate.lat} | Longitude: ${location.coordinate.lon}`)
}
为了更好地理解,我调整了代码中的一些名称。出于某种原因,Object.keys()
返回给定对象的所有键。在您的示例中,这是一个数组,其值将是0, 1, 2, ...
。如果您对数组中的一个对象执行此操作,例如Object.keys(locations[0])
,您将得到以下内容:name, type, rating, coordinate
。lat
和lan
不会在那里,因为它们是coordinate
的嵌套属性。我建议你,你告诉自己一点关于javascript循环,因为它们是非常重要的。