【问题标题】:How to access properties in array of objects in react/javascript For-Loop & ForEach?如何在 react/javascript For-Loop 和 ForEach 中访问对象数组中的属性?
【发布时间】:2021-08-10 14:27:08
【问题描述】:

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

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

Google Maps 的 Post 数据结构:数组 --> 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

【问题讨论】:

  • 这个问题还不够清楚,你能再澄清一下吗? “尝试遍历数组并访问数据,但没有 console.log”
  • 像返回/打印一样迭代数据
  • 根据这些数据,您期望的确切结果是什么?
  • 这能回答你的问题吗? For-each over an array in JavaScript

标签: javascript reactjs for-loop


【解决方案1】:

我会使用地图,因为您希望位置成为关键。所以输出类似于 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"
.... 
*/

【讨论】:

    【解决方案2】:

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

    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>
            ))}
      

      一个例子here

      【讨论】:

        【解决方案4】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-02
          • 2019-10-25
          • 1970-01-01
          • 2017-06-28
          • 2013-12-02
          • 1970-01-01
          • 2019-10-15
          • 1970-01-01
          相关资源
          最近更新 更多