简体   繁体   中英

Why am I getting the same object pushed into my array?

I'm trying to build an array of places from Yelp's response. However, after pushing and passing my array into the callback to be returned I end up with the same 4 places instead of 4 unique places.

    let rawResult = arrayBusinesses.jsonBody.businesses;
    let arrVenues = new Array();
    // console.log(rawResult);
    let venue = {
        type: 'venue',
        id: '',
        latitude: null,
        longitude: null,
        title: '',
        address: ''
       // thumb_url: ''
    };


    for (let i = 0; i < 5; i++) {
        console.log('i', i);
        (function(j){
            console.log('j' + j);
            let bus = rawResult[j];
            venue.type = 'venue';
            venue.id = j+'a';
            venue.latitude = bus.coordinates.latitude;
            venue.longitude = bus.coordinates.longitude;
            venue.title = bus.name;
            venue.address = bus.location.address1;
            arrVenues.push(venue);
        })(i);
    }

your code is hard to read how about something like

const arrVenues = rawData.slice(0, 5)
.map((place, index) => (
  {
    type: 'venue',
    id: `${index}a`,
    latitude: place.coordinates.latitude,
    longitude: place.coordinates.longitude,
    title: place.name',
    address: place.location.address,
 }
));

How ever to answer your question the problem is that you keep pushing the same object every time. when you do arrVenues.push(venue) is always the same object, literally the same memory location. since you never take time to make a copy of the object and just modify is properties you end up with an array of the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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