kb_
kb_

Reputation: 187

Update array item value from function results - javascript

I have an array of objects, where I need one value from each object to be updated with the results of a function.

function deg2rad(deg) {
    return deg * (Math.PI / 180)
}
function getDistanceFromStore(userLat, userLon, storeLat, storeLon) {
    var R = 3958.8; // Radius of the earth in miles
    var dLat = deg2rad(storeLat - userLat);  // deg2rad below
    var dLon = deg2rad(storeLon - userLon);
    var a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(storeLat)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2)
        ;
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c; // Distance in miles
    return d;
}

Array:

const locations = [
    {
        location: "One",
        lat: 19.7517133,
        lng: -95.3241383,
        distance: '',
    },
    {
        location: "Two",
        lat: 19.7883441,
        lng: -95.8037025,
        distance: '',
    },
    {
        location: "Three",
        lat: 20.1523784,
        lng: -95.4474075,
        distance: '',
    },
    {
        location: "Four",
        lat: 19.53731909999999,
        lng: -95.1523701,
        distance: '',
    },
];

I need the function to execute for each array object and update the distance value with the resulting of the function. I haven't been able to find an answer anywhere so far.

I also have the component this is going into, where I am fetching user location data:

const Menu = () => {
    const [hasError, setErrors] = useState(false);
    const [userLocation, setUserLocation] = useState({});

    useEffect(() => {
        async function fetchData() {
            const res = await fetch('http://api.ipapi.com/api/check?access_key=' + access_key);
            res
                .json()
                .then(res => setUserLocation(res))
                .catch(err => setErrors(err));
        }
        fetchData();
    }, []);

    var userLat = userLocation.latitude;
    var userLon = userLocation.longitude;
}

I'm guessing I should be getting the use data outside of the component, but I am not sure how to do that.

Upvotes: 0

Views: 47

Answers (1)

Janiis
Janiis

Reputation: 1576

You have to use map function on locations to get new updated version of locations. Here is some basic idea.

I think you have to use some ReactContext to store userLat and userLon in global state, so you can use it in your react app.

const locationsUpdated = locations.map(item => {
  const newDistance = getDistanceFromStore(userLat, userLon, item.lat, item.lng);
  return {
    ...item
    distance: newDistance
  }
});

console.log(locationsUpdated);

Upvotes: 3

Related Questions