CRod
CRod

Reputation: 315

How to create an array of objects with a for loop

I have a array of objects called listData that I would like to call certain information from into a separate called markers.

var markers = [];
for(let i=0;i<listData.length;i++){
    markers.push({
        latitude:this.state.listData[i].geometry.location.lat,
        longitude:this.state.listData[i].geometry.location.lng,
        title:this.state.listData[i].name
    });
}

but it is not working.

Upvotes: 0

Views: 60

Answers (3)

james emanon
james emanon

Reputation: 11807

I like to use "map" for such data returns. Nothing wrong with what others posted, I just like this concise syntax a bit better. I am assuming you are referencing the initially value incorrectly. You didn't use this.state.listData in your loop.

var markers = this.state.listData.map(function(v){
    return {
       latitude:v.geometry.location.lat,
       longitude:v.geometry.location.lng,
       title:v.name
    }
})

Upvotes: 3

M.Tanzil
M.Tanzil

Reputation: 1995

Try this, i think this is what you want.

Remove this and start the hierarchy from state, if its not helping you can remove both this.state and start afterwords.

var markers = [];

for(var i = 0; i < 5; i++){
 markers.push(
   {
    latitude:'0123',
    longitude:'0345' 
   });
}

console.log(markers);

Change and Add values as you desire for yourself.

Upvotes: 0

Christos
Christos

Reputation: 53958

From your code, I assume that you need something like the following:

for( let i=0; i < listData.length; i++ ){
    markers.push(
    {
        latitude: listData[i].geometry.location.lat,
        longitude: listData[i].geometry.location.lng,
        title: listData[i].name
    }
);

You just want to loop through listData and add for each item of this array (or array like object) a new object to the markers array. So I don't get why you used this.state to access the listData.

Upvotes: 0

Related Questions