0

I am trying to take two pieces of data from an object and push it as a new object into an array. The data is being supplied by an API call to my SQL database. That API call is working correctly and displaying the object in a console table. When the script runs a forEach method to extract the data into its own object and then push that new object to a new array, the new array returns "undefined". Code below:

Example data (only one placeholder entry currently, the events array will be seeded with multiple examples in this format)

events = [{location: "Emergency Shelter", latitude: "37.5434", longitude: "-77.4435"}]

Empty arrays declared and API call functioning properly:

let events = [];
let locations = [];

$.get("/api/events", data => {
 for (let i = 0; i < data.length; i++) {
   events.push(data[i]);
 }
});

console.table displays the object correctly and includes the keys "latitude" and "longitude" with the correct corresponding values

forEach method:

locations = events.forEach(location => {
  const coords = {};
  coords.latitude = location.latitude;
  coords.longitude = location.longitude;
  locations.push(coords);
});
console.log("Coordinates list: " + locations);

console.log displays "Coordinates list: undefined"

I feel like I may be missing a return somewhere, but I'm not sure where. I tried adding

return locations;

inside the forEach method but it doesn't change anything (and I believe that would exit my function prior to getting through the entire array). Any help is appreciated!

5
  • events is not an array, but an object. Are you sure about that? Commented Dec 1, 2020 at 18:02
  • It is an array of objects. Was missing brackets around my example data. Just edited. Commented Dec 1, 2020 at 18:06
  • This is quite straight forward. Please try to run my updated answer. Commented Dec 1, 2020 at 18:08
  • Part of the issue was a scope problem inside the API call. Events was an empty array outside of the API function. I have corrected that and now console.log(events) displays the objects correctly outside of the API function. I have tried both the map approach and the foreach approach @baymax and Peter Seliger have provided and still the console.log(locations) just displays an empty array. Thank you both for the continued help on this. Commented Dec 1, 2020 at 19:31
  • It is now working using the map method. It seems odd to me, but the solution was to run the map method after also pushing the values inside of the API call as shown below. If I remove one or the other, the array is empty. Seems redundant, but it works. $.get("/api/events", data => { for (let i = 0; i < data.length; i++) { events.push(data[i]); locations.push({ id: data[i].id, latitude: data[i].latitude, longitude: data[i].longitude }); } }); Commented Dec 1, 2020 at 20:28

2 Answers 2

3

forEach returns nothing so locations should be undefined. You shouldn't pass return value of forEach to locations

events.forEach(location => {
  const coords = {};
  coords.latitude = location.latitude;
  coords.longitude = location.longitude;
  locations.push(coords);
});
console.log("Coordinates list: " + locations);

Also you can use map function.

const events = [
  { location: 'Emergency Shelter', latitude: '37.5434', longitude: '-77.4435' }
];
const locations = events.map(({ latitude, longitude }) => ({
  latitude,
  longitude
}));

console.log(locations);

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the reply. So how would I get the coords object into the locations array when I need the location function to loop through the existing array called events and grab each set of coordinates?
I think my answer should work. After forEach function you will get locations array with coordinates.
Aha, Thanks again. I see, the forEach should just be run as a method on events and not defining the locations array. I made the adjustment and now it displays "Coordinates list: [object Object].
You will see [object Object] for array when it is logged. If you want to see the full log you can use console.log(JSON.stringify(locations))
"Thanks for the reply. So how would I get the coords object into the locations array when I need the location function to loop through the existing array called events and grab each set of coordinates?" ... Try a map based approach which also would condense your code to ... const locations = events.map(({ latitude, longitude }) => ({ latitude, longitude }));
|
1

Try a map based approach which also would condense your code to ...

const events = [{
  location: "Emergency Shelter",
  latitude: "37.5434",
  longitude: "-77.4435"
}, {
  location: "Peopl's Kitchen",
  latitude: "36",
  longitude: "-78"
}, {
  location: "Salvation Army",
  latitude: "38",
  longitude: "-76"
}]; 

const locations = events.map(({ latitude, longitude }) => ({ latitude, longitude }));

console.log("Coordinates list: ", locations); // do not concatenate the result.
console.log("Coordinates list: " + locations);
console.log("Coordinates list: " + JSON.stringify(locations));
.as-console-wrapper { min-height: 100%!important; top: 0; }

map creates a new array by iterating another one where each item of the new array equals the return value of the mapping/transforming function which, at each iteration step, does process the current value of the original array.

4 Comments

Thanks Peter. So that changed it a little bit. The console log is now showing "Coordinates list: " (basically, not displaying undefined but also not capturing the coords data pushed into locations
maybe you provide boiled down test data for your events array (a list of 3 event/location items will do it) ... than one was capable of verifying/demonstrating the provided different approaches.
Sure thing: added to original post
the logging of [object Object], [object Object], [object Object] is due to your code that concatenates the locations result ... console.log("Coordinates list: " + locations) whereas it needs to be console.log("Coordinates list: ", locations) in order to log some readable data structure(s).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.