Javascript搜索数组对象//我如何获得控制台日志,只记录代码中至少4.0英里的路径



尝试使用过滤器方法来查找hikingBermudaObject中至少4英里的路径。有更好的方法吗?

const hikingBermuda = {
author: "Cecile Davidson",
price: 17.95,
title: "Hiking Bermuda",
sections: {
0: {
sectionName: "Preface",
chapters: [
{
name: "Trail Locator",
page: 12,
},
],
},
1: {
sectionName: "Introduction",
chapters: [
{
name: "Map Legend",
page: 24,
},
{
name: "Rating System",
page: 22,
},
],
},
2: {
sectionName: "West End",
chapters: [
{
name: "Botanical Gardens",
page: 63,
},
{
name: "Rockaway, Whale Bay Park",
page: 45,
},
{
name: "Somerset Bridge, Hog Bay Park",
page: 39,
},
],
},
},
trails: [
{
name: "Somerset to Hamilton Railway Trail",
page: 75,
section: "West End",
distanceInMiles: 11.7,
rating: "Hardy",
},
{
name: "City of Hamilton",
page: 69,
section: "West End",
distanceInMiles: 2.4,
rating: "Easy",
},
{
name: "St. George's Point",
page: 131,
section: "East End",
distanceInMiles: 3.6,
rating: "Moderate",
},
{
name: "South Shore Beaches",
page: 53,
section: "West End",
distanceInMiles: 5.0,
rating: "Moderate",
},`enter code here`
],`enter code here`
};

描述

上面的JSON中存在一些错误。

下面是一个例子,说明这对于JavaScript的Array.filter函数来说是一个很好的用例。

示例

const hikingBermuda = {
author: 'Cecile Davidson',
price: 17.95,
title: 'Hiking Bermuda',
sections: {
0: {
sectionName: 'Preface',
chapters: [{
name: 'Trail Locator',
page: 12
}]
},
1: {
sectionName: 'Introduction',
chapters: [{
name: 'Map Legend',
page: 24
},
{
name: 'Rating System',
page: 22
}
]
},
2: {
sectionName: 'West End',
chapters: [{
name: 'Botanical Gardens',
page: 63
},
{
name: 'Rockaway, Whale Bay Park',
page: 45
},
{
name: 'Somerset Bridge, Hog Bay Park',
page: 39
}
]
}
},
trails: [{
name: 'Somerset to Hamilton Railway Trail',
page: 75,
section: 'West End',
distanceInMiles: 11.7,
rating: 'Hardy'
},
{
name: 'City of Hamilton',
page: 69,
section: 'West End',
distanceInMiles: 2.4,
rating: 'Easy'
},
{
name: "St. George's Point",
page: 131,
section: 'East End',
distanceInMiles: 3.6,
rating: 'Moderate'
},
{
name: 'South Shore Beaches',
page: 53,
section: 'West End',
distanceInMiles: 5.0,
rating: 'Moderate'
}
]
}
const mileLimit = 4
const trails = hikingBermuda.trails.filter((el) => {
return el.distanceInMiles <= mileLimit
})
console.log(trails)

最新更新