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

sq1bmfud  于 2022-12-12  发布在  React
关注(0)|答案(4)|浏览(164)

尝试循环数组并访问数据,但没有console.log

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

谷歌MapPost的数据结构:数组--〉对象

[
    {
        "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"
    }
]

要存储的数据:地点:地点--〉地点.title

v440hwme

v440hwme1#

我会使用Map,因为您希望位置是一个关键字。所以输出将是类似于location { lat,lng } -〉title的内容

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"
.... 
*/
kr98yfug

kr98yfug2#

这可以通过直接访问对象IE:

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
编辑:代码打错了,我已经很长时间了,没有意义,但万一有新的人需要帮助...

jei2mxaa

jei2mxaa3#

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

{locations?.data?.map((item) => (
        //  console.log(item);

        <div>{item.title}</div>
      ))}

here示例

sczxawaw

sczxawaw4#

假设您有一个名为Locations的变量,您可以执行以下操作:

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

并在闭包中执行任何需要执行的操作。

相关问题