开发者问题收集

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

2021-08-10
588

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

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

Google 地图帖子的数据结构: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"
    }
]

想要存储数据:地点:Locations --> Places.title

3个回答

我会使用地图,因为您希望位置作为键。因此输出将类似于 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"
.... 
*/
c2devBj
2021-08-10

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

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

编辑:代码输入错误,我知道这已经很久了,没有意义,但以防万一有新人需要帮助..

anirudh_techie
2021-08-10

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

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

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

示例 此处

RABI
2021-08-10