Ways to loop through a collection of indexed elements

I am working with an array of indexed objects and my goal is to iterate through it in order to transform it into a new flattened array.

Here is the initial array of objects:

"attentionSchedules": [
    {
        "room": "1",
        "schedules": [
            {
                "days": [
                    "SA",
                    "WE"
                ],
                "_id": "6271xxxx",
                "initialTimeStr": "12:00 am",
                "finalTimeStr": "12:00 am",
                "initialTime": "2022-05-03T06:00:00.000Z",
                "finalTime": "2022-05-03T06:00:00.000Z"
            }
        ],
        "place": {
            "loc": {
                "type": "Point",
                "coordinates": [
                    -88.03xxx,
                    15.49xxx
                ]
            },
            "_idPlace": "5d5ba845xxx",
            "name": "Labs",
            "address": "xxx"
        },
        "floor": 1
    },
    {
        "room": "23",
        "floor": 1,
        "schedules": [
            {
                "days": [
                    "MO",
                    "TH",
                    "WE",
                    "YOU",
                    "FR",
                    "SA"
                ],
                "_id": "62754264a627af5fc44286b3",
                "initialTimeStr": "08:00 am",
                "finalTimeStr": "09:00 pm",
                "initialTime": "2022-05-06T14:00:00.000Z",
                "finalTime": "2022-05-07T03:00:00.000Z"
            }
        ],
        "place": {
            "loc": {
                "type": "Point",
                "coordinates": [
                    -88.02xxx,
                    15.50xxx
                ]
            },
            "_idPlace": "ba",
            "name": "Labs",
            "address": "xx"
        }
    }
],

The desired output object looks like this:

{
    lng: -88.02xxx,
    lat: 15.50xxx,
    _idPlace: "ba"
}
.
.
.
N

I attempted to achieve this by implementing the following method using Angular and JavaScript/Typescript:

let locCoord: any[] = [];
this.attentionSchedules?.forEach(elm => {
    for (const [key, value] of Object.entries(elm.place.loc)) {
        let lng = value[0];
        let lat = value[1];

        let dataObjLoc = {
            _id: elm.place._id,
            lat: lat,
            lng: lng
        }

        locCoord.push(dataObjLoc);
    }
});
console.log(locCoord);

However, the current output is not as expected since Object.entries duplicates the keys. Can anyone assist me in solving this issue? Thank you.

Answer №1

I think there might be a more direct way to extract the values without looping over Object.entries(elm.place.loc). Check out this alternative approach:

const attentionSchedules = [{"room":"1","schedules":[{"days":["SA","WE"],"_id":"6271xxxx","initialTimeStr":"12:00 am","finalTimeStr":"12:00 am","initialTime":"2022-05-03T06:00:00.000Z","finalTime":"2022-05-03T06:00:00.000Z"}],"place":{"loc":{"type":"Point","coordinates":[-88.03,15.49]},"_idPlace":"5d5ba845xxx","name":"Labs","address":"xxx"},"floor":1},{"room":"23","floor":1,"schedules":[{"days":["MO","TH","WE","YOU","FR","SA"],"_id":"62754264a627af5fc44286b3","initialTimeStr":"08:00 am","finalTimeStr":"09:00 pm","initialTime":"2022-05-06T14:00:00.000Z","finalTime":"2022-05-07T03:00:00.000Z"}],"place":{"loc":{"type":"Point","coordinates":[-88.02,15.5]},"_idPlace":"ba","name":"Labs","address":"xx"}}];

let locCoord = [];
attentionSchedules?.forEach(({ place }) => {
  const [lng, lat] = place.loc.coordinates;
  
  locCoord.push({
    _id: place._idPlace,
    lat: lat,
    lng: lng
  });
});
console.log(locCoord);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating form components in a row

I'm currently working on an app and I'm attempting to align 3 form elements in a ratio of 25/25/50, but it's proving to be quite challenging. At the end of this message, you'll find a picture showing the current layout. Additionally, I& ...

Encountering an error when attempting to generate a production build after running the npm install command with the

After adding the brotli-webpack-plugin as a devDependency, I encountered an issue when attempting to generate a production build using npm run build (which internally runs next build). The error message displayed was: Error: Cannot find module 'bro ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

When the mouse drags across the empty space, the force graph continually jumps

I have some questions. I utilized a force graph and added zoom functionality to it. However, when I drag the mouse over the blank area, the force graph keeps jumping erratically. like this Is there a way to prevent the graph from jumping? Thank you. ( ...

A step-by-step guide on utilizing links for downloading PDF files in Vue/Nuxt

Having some trouble opening a PDF tab in my Vue application with NUXT and Vuetify... any suggestions? I attempted to use: <a href="../static/docs/filename.pdf" target="_blank">Download PDF</a> I also tried using <nuxt-link> but it didn ...

What is the process for discovering the kinds of models that can be generated with a Prisma client?

Ensuring data type correctness when creating a Prisma model named 'bid' is crucial. With auto-generated prisma types available, understanding the naming convention and selecting the appropriate type can be confusing. The bid schema looks like th ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

AWS Lambda applies quotes to create the event input

I'm encountering a problem with my Python 3.8 AWS Lambda function that is meant to handle form inputs from a web application. The data from the form inputs gets passed to the Lambda function and ends up in the event dictionary. However, lambda seems t ...

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

The log indicates that there are two distinct IP addresses associated with the user

I find that this question may be better suited for another Stack Exchange board, and I am open to migrating it there if needed. In the development of a web application, we record certain event information to assist in diagnosing any potential issues. One ...

Identifying Ctrl+V in VueJS: A Guide

Although I found the answers to this question, they were for jQuery and not suitable for my needs with vue.js. Currently, I have successfully implemented code to detect single character presses: export default { name: 'game', data () { ...

What is the best way to generate inner HTML components within Angular by creating components?

I want to create a custom component that functions similarly to Material Tabs. I currently can use Material Tabs to create tabs like this <mat-tab-group mat-align-tabs="center"> <mat-tab label="First Tab"> <p& ...

Is it possible to create a replicating text box in AngularJS that multiplies when entering input

I am experimenting with creating a sequence of text boxes that dynamically generate new empty text boxes as the user enters information into each one. Each text box is required to have an ng-model value associated with it, and they should all be generated ...

How to send information to a modal component in ReactJS?

I'm feeling a bit lost here, maybe I'm missing something. What I am trying to achieve is a loop that populates an array with progress bar elements and then displays them with the relevant information. When a user clicks on a progress bar, the d ...

The product image does not display any other images

Hey, I'm experiencing an issue and need help replicating the photo changing effect on this website: I've managed to do everything right except for the photo changing feature (1 / 2 / 3 / 4)!! Here's what I have so far: Can anyone assist m ...

Opt for utilizing a global npm package over repeatedly installing it

Is there a way to utilize the globally installed package without needing to reinstall it every time we run npm i? Here's the scenario I have: I've set up a docker image with a specific package already installed (installation command in the Docker ...

Error occurs when React-router 6 cannot render an error component

I'm facing an issue in my React app where the custom error component I created for unmatched routes is not being rendered, instead the default error page appears. Here's a snippet of how my BrowserRouter is set up: const router = createBrowserRo ...

Tips for transforming alphanumeric characters into value ranges using Typescript

myArray = ["AB01","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"]; // code snippet to create expected string: "AB01-AB04, AB11, BC12-BC13, SB33" The array contains combinations of one or two letter characters followed by two or three digits. Examples ...