如何在 react/javascript For-Loop & ForEach 中访问对象数组中的属性?



尝试遍历数组并访问数据,但没有console.log

for (let i = 0; i < Locations.length; i++) {
console.log(Locations[i]);
}

Post for Google Maps的数据结构:Array—>Obj

[
{
"description": "asdlafaslfj",
"lat": 28.0440005,
"lng": -82.3992308,
"title": "tent"
},
{
"description": "asdadf",
"lat": 28.050104,
"lng": -82.39597859999999,
"title": "Blanket"
},
{
"description": "sadfasf",
"lat": 29.6900252,
"lng": -82.3733803,
"title": "Swamp"
},
{
"description": "9808",
"lat": 29.6900252,
"lng": -82.3733803,
"title": "Dorm"
},
{
"description": "ssljkfasf",
"lat": 29.6900252,
"lng": -82.3733803,
"title": "Treehouse"
},
{
"description": "asdlafaslfj",
"lat": 29.6900252,
"lng": -82.3733803,
"title": "tent"
}
]

想要存储数据:Places: Locations——>Places.title

如果您希望位置为键,则使用地图。因此输出将是类似于location {lat, lng} ->标题

const res = places.reduce((acc, val) => {
const location = { lat: val.lat, lng: val.lng};
acc.set(location, val.title);
return acc;
}, new Map());
console.log(res);
/* Outp
0: {Object => "tent"}
key: {lat: 28.0440005, lng: -82.3992308}
value: "tent"
.... 
*/

这可以通过直接访问对象来实现即:

for (let i = 0; i < Locations.length; i++) {
var currentLocation = Locations[i];
var title = currentlocation.title;
//this can also be achieved using
Locations[i].title
}

感谢您的阅读<3

编辑:代码有一个错误的类型,好像它已经很长时间了,没有意义,但万一有新的人需要帮助…

我相信你正在尝试从数组中显示位置标题列表。为此,您可以使用map()函数。

{locations?.data?.map((item) => (
//  console.log(item);
<div>{item.title}</div>
))}

这里有一个例子

假设您有一个名为Locations的变量,您可以这样做:

Locations.forEach(loc => console.log(loc.description));

,并在该闭包中执行任何需要执行的操作。以控制台日志为例。

相关内容

  • 没有找到相关文章

最新更新