0

Trying to loop over the array and access data but without the console.log

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

Data structure of 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"
    }
]

Want to store data: Places: Locations --> Places.title

Kug
  • 23
  • 5
  • 2
    The question is not clear enough, could you clarify this a bit more? "Trying to loop over the array and access data but without the console.log" – Ryan Le Aug 10 '21 at 14:30
  • Iterate over the data like a return/print – Kug Aug 10 '21 at 14:32
  • 1
    What is the exact outcome you are expecting given this data? – sebtheiler Aug 10 '21 at 14:32
  • Does this answer your question? [For-each over an array in JavaScript](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – Erik Aug 10 '21 at 14:39

4 Answers4

2

I would go with a map as you want the location to be a key. So output would be something like 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
  • 66
  • 4
1

this can be achieved by directly accessing the object 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
}

Thank you for reading <3

edit: code had a mistype, ik its been a long time and there's no point but incase there's someone new who needs help..

0

I believe you are trying to display list of location title from the array. For that you can use map() function.

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

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

An example here

RABI
  • 692
  • 2
  • 15
0

Assuming you have a variable named Locations you can do this:

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

and do whatever you need to do in that closure. Left the console log as an example.

Erik
  • 1,246
  • 13
  • 31