繁体   English   中英

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

[英]How to access properties in array of objects in 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

我会用 go 和 map 因为你希望这个位置是一个关键。 所以 output 类似于 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"
.... 
*/

这可以通过直接访问 object 来实现,即:

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() function。

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

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

这里的一个例子

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

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

并在那个闭包中做任何你需要做的事情。 以控制台日志为例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM