Combining an array of objects into a single object and organizing shared information into an array

Essentially, I have an array of objects structured as follows:

connectionInfo: any = [
    {
      "deviceName": "transponder1",
      "ports": 4,
      "rowNo": 1,
      "columnNo": 1,
      "posX": 2060.5,
      "posY": 200,
      "portInfo": {
        "portNumber": "1",
        "x": "2260.5",
        "y": "261.6666666666667"
      }
    },
    {
      "deviceName": "transponder1",
      "ports": 4,
      "rowNo": 1,
      "columnNo": 1,
      "posX": 2060.5,
      "posY": 200,
      "portInfo": {
        "portNumber": "2",
        "x": "2260.5",
        "y": "395"
      }
    },
    {
      "deviceName": "transponder1",
      "ports": 4,
      "rowNo": 1,
      "columnNo": 1,
      "posX": 2060.5,
      "posY": 200,
      "portInfo": {
        "portNumber": "3",
        "x": "2260.5",
        "y": "528.3333333333334"
      }
    }
];

The desired output should be in the following format:

{
  "deviceName": "transponder1",
  "ports": 4,
  "rowNo": 1,
  "columnNo": 1,
  "posX": 2060.5,
  "posY": 200,
  "portInfo": {
    "portNumber": "1",
    "x": "2260.5",
    "y": "261.6666666666667"
  },
  "allPortsInfo": [
    {
      "portNumber": "1",
      "x": "2260.5",
      "y": "261.6666666666667"
    },
    {
      "portNumber": "2",
      "x": "2260.5",
      "y": "395"
    },
    {
      "portNumber": "3",
      "x": "2260.5",
      "y": "528.3333333333334"
    },
    {
      "portNumber": "4",
      "x": "2260.5",
      "y": "528.3333333333334"
    }
  ]
}

My attempt involved using the following code snippet:

const cInfo = this.connectionInfo.reduce((acc, value) => acc.concat(value.portInfo),[]);

However, with the above approach, the output ends up being:

[
  {
    "portNumber": "1",
    "x": "2260.5",
    "y": "261.6666666666667"
  },
  {
    "portNumber": "2",
    "x": "2260.5",
    "y": "395"
  },
  {
    "portNumber": "3",
    "x": "2260.5",
    "y": "528.3333333333334"
  },
  {
    "portNumber": "4",
    "x": "2260.5",
    "y": "528.3333333333334"
  }
]

I utilized reduce to gather all portInfo into an array, however, achieving the expected output within the reduce loop remains uncertain.

You can view my code on StackBlitz

Answer №1

To enhance an already grouped array, you can select the first element as an object and insert a new property by specifically mapping the portInfo attribute.

var data = [[{ deviceName: "transponder1", ports: 3, rowNo: 1, columnNo: 1, posX: 2060.5, posY: 200, portInfo: { portNumber: "1", x: "2260.5", y: "261.6666666666667" } }, { deviceName: "transponder1", ports: 3, rowNo: 1, columnNo: 1, posX: 2060.5, posY: 200, portInfo: { portNumber: "2", x: "2260.5", y: "395" } }, { deviceName: "transponder1", ports: 3, rowNo: 1, columnNo: 1, posX: 2060.5, posY: 200, portInfo: { portNumber: "3", x: "2260.5", y: "528.3333333333334" } }], [{ deviceName: "amplifier1", ports: 3, rowNo: 1, columnNo: 2, posX: 2860.5, posY: 200, portInfo: { portNumber: "1", x: "3060.5", y: "261.6666666666667" } }, { deviceName: "amplifier1", ports: 3, rowNo: 1, columnNo: 2, posX...
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Using EmailValidator in Ionic 3

Recently, I noticed that the Angular dev team has introduced a new feature called EmailValidator in the latest Ionic framework update. However, I'm finding it a bit confusing on how to implement it. Can anyone provide me with an example of how to use ...

How to retrieve an array using a for loop in Jquery

Hey there! I'm working on a project where I need to loop through two arrays - one for button IDs and the other for text. However, I've run into an issue where it's unable to iterate through the text array. Whenever I try to use window.alert ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...

What are the limitations of sorting by price?

One issue I am facing is that the sorting functionality in the sortProductsByPrice (sortOrder) method doesn't work properly when products are deleted or added. Currently, sorting only applies to products that are already present in the this.products a ...

Steps for building a custom component using MUI as a foundation

My current approach: import React from "react"; import {useHistory} from "react-router-dom"; import {Button, ButtonProps} from "@mui/material"; type Props = { label?: string } & ButtonProps; export const NavBackButton = ...

Encountering an issue with multi ./src/styles.scss during the deployment of my Angular application on Heroku

My attempt to deploy my Angular app on Heroku is resulting in an unusual error. I've experimented with changing the styles path in angular.json, but it hasn't resolved the issue. I suspect it's a path problem, yet I can't seem to corre ...

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

AngularJS Dropdown multiselect is experiencing delays in loading

I have been utilizing the AngularJS Dropdown Multiselect from a certain URL, and I've noticed that for lists containing more than 500 options, the dropdown loading time is excessively slow. It takes a whole minute just to display the available options ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Using Typescript with MongoDB's JSON schema

Exploring the usage of MongoDB's $jsonschema validator with npm's json-schema-to-typescript has me intrigued. However, I've noticed that MongoDB utilizes bsontype instead of type, which may introduce additional differences that are currently ...

Tips for refreshing the current page with passing a parameter in the URL?

To achieve the functionality of reloading the page whenever different buttons are pressed and sending a String to the same page, I need to take that String on created() and use it to send an HTTP Get into my Database. My current setup looks like this: exp ...

What are some alternatives for integrating React production build files apart from utilizing Express?

Is there a way to integrate React into my library using the HTTP module? I'm trying to figure out how to recursively send static files. Specifically, I want to include the build folder from the React production build, but I'm not sure how to go a ...

Troubleshooting a Mystery JavaScript Reference Error in a Date and Time Application

Currently, I am working on developing a JavaScript file to create variables for dates and times using the shortcut method. Although everything seems to be in order from what I can see, it does not display correctly, and when checked with Google Chrome&apos ...

Error in Winston: Unable to determine the length of undefined property

I encountered an issue with my Winston Transport in the express backend of my MERN app. The error message reads: error: uncaughtException: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefi ...

NGXS: Issue with passing objects to "setState" occurs when any of the patched inner fields is nullable or undefined

In my Angular components, I have created a class that is responsible for storing the state: export class MyStateModel { subState1: SubStateModel1; substate2: SubStateModel2; } This class has simple subclasses: export class SubStateModel1 { someField ...

Using Django for Underscore and Backbone templating

When I define my JavaScript templates within: <script type="text/template"> </script> they are not rendered in the HTML (I don't see them on the page) in my Django application. Could one of the filters or middlewares I have declared be e ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

How to stop the previous page from reloading with Express.js routing?

Just starting out with express and web development in general, I have a question regarding routing. Currently, I am working on a web app using Firebase with pure JS and implementing routing on Firebase cloud functions. The routing logic is outlined below: ...

One Functionality on Button is Failing to Execute among Several Tasks

I've encountered an issue with one of the tasks triggered by a button click. The button successfully executes two out of three tasks (hides them on click), except for the last task which involves a text-blinking JavaScript function. I've used the ...

Creating a PHP and MySQL powered drop-down menu that features multiple columns

I am looking to create a dropdown menu with multiple columns. The options data is retrieved from MySQL using PHP. Below is the code I have: $query = mysql_query("SELECT * FROM accounts"); <select class="form-dropdown validate[required]" style="widt ...