Combining attributes of objects in an array

Is the title accurate for my task? I have an array structured like this:

{
  "someValue": 1,
  "moreValue": 1,
  "parentArray": [
    {
      "id": "2222",
      "array": [
        {
          "type": "test",
          "id": "ID-100"
        },
        {
          "type": "test1",
          "id": "ID-200"
        }
      ]
    },
    {
      "id": "5555",
      "array": [
        {
          "type": "test",
          "id": "ID-100"
        },
        {
          "type": "test1",
          "id": "ID-200"
        }
      ]
    },
    {
      "id": "444",
      "array": [
        {
          "type": "test",
          "id": "ID-100"
        },
        {
          "type": "test1",
          "id": "ID-200"
        }
      ]
    }
  ]
}

I aim to merge all "array" properties into a new array, resulting in a structure similar to this:

{
  "someValue": 1,
  "moreValue": 1,
  "array": [
    {
      "type": "test",
      "id": "ID-100"
    },
    {
      "type": "test1",
      "id": "ID-200"
    },
    {
      "type": "test",
      "id": "ID-4400"
    },
    {
      "type": "test1",
      "id": "ID-500"
    },
    {
      "type": "test",
      "id": "ID-600"
    },
    {
      "type": "test1",
      "id": "ID-700"
    }
  ]
}

What would be the optimal method to consolidate these properties using Typescript? I'm seeking a Typescript/Angular-friendly solution as this data needs to be utilized to generate HTML elements.

Answer №1

If you want to combine inner arrays within your parentArray, you can achieve this by utilizing the reduce method:

let object = {
      "someValue": 1,
      "moreValue": 1,
      "parentArray": [
        {
          "id": "2222",
          "array": [
            {
              "type": "test",
              "id": "ID-100"
            },
            {
              "type": "test1",
              "id": "ID-200"
            }
          ]
        },
        {
          "id": "5555",
          "array": [
            {
              "type": "test",
              "id": "ID-100"
            },
            {
              "type": "test1",
              "id": "ID-200"
            }
          ]
        },
        {
          "id": "444",
          "array": [
            {
              "type": "test",
              "id": "ID-100"
            },
            {
              "type": "test1",
              "id": "ID-200"
            }
          ]
        }
      ]
    }

    let newObject = {
        someValue: object.someValue,
        moreValue: object.moreValue,
        array: object.parentArray.reduce((previous, current) => [...previous, ...current.array],[])
    }
    
    console.log(newObject)

Answer №2

Here is an alternative approach:

const data = {
  valueA: 1,
  valueB: 1,
  mainArray: [
    {
      id: "1111",
      items: [
        {
          category: "example",
          itemId: "ID-123"
        },
        {
          category: "sample",
          itemId: "ID-456"
        }
      ]
    },
    {
      id: "2222",
      items: [
        {
          category: "example",
          itemId: "ID-123"
        },
        {
          category: "sample",
          itemId: "ID-456"
        }
      ]
    },
    {
      id: "3333",
      items: [
        {
          category: "example",
          itemId: "ID-123"
        },
        {
          category: "sample",
          itemId: "ID-456"
        }
      ]
    }
  ]
};

let newData = {
  ...data,
  items: Object.values(data.mainArray).flatMap(item => item.items)
};

delete newData.mainArray;

console.log(newData);

Answer №3

If you need to transform data, consider using a mapping function. Personally, I find lodash to be quite handy in these situations. You can check out the documentation here: https://lodash.com/docs/4.17.15#flatMap

const destination = {
    someValue: source.someValue,
    moreValue: source.moreValue,
    array: _.flatMap(source.parentArray, (value) => value.array)
};

Answer №4

If you want to extract values using map, use the following code:

this.data.parentArray.map(item => item.array)
:

Here is an example:

var result = {
  someValue: this.data.someValue,
  moreValue: this.data.moreValue,
  array: this.data.parentArray.map(item => item.array)
};

See Working Demo Here

Answer №5

If you want to test out the next solution (which supports "infinite" nesting), give this a try:

function collectDescendants(inputArr) {
  return inputArr.reduce((output, element) => [...output, ...(element.array ? collectDescendants(element.array) : [element])], []);
}

Then simply use the function like so:

collectDescendants(your_object.parentArray);

See Demo Here

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

Retrieving JSON data in Angular 5 returns a 400 bad request error

Having trouble calling the REST API of Amazon S3 from Angular 5. Keep getting a 400 bad request error. This problem has been persisting for a while now and I really need to find a solution or at least get some suggestions on where the issue might be. Her ...

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...

Tips for optimizing file sizes in an Angular 11 app for production deployment

Currently, I am troubleshooting an issue with my application where some of my production files are taking a long time to load. I have already deployed my application and tried using the --aot and optimizer commands during the production build process. Here ...

Unable to simultaneously execute TypeScript and nodemon

Currently, I am in the process of developing a RESTful API using Node.js, Express, and TypeScript. To facilitate this, I have already installed all the necessary dependencies, including nodemon. In my TypeScript configuration file, I made a modification to ...

"Data in Fusioncharts appears to be correctly formatted, but it is having difficulties

I am developing a financial analysis tool and I need to visualize stock data using fusion charts. Currently, my dataset includes stock values along with their respective dates: $scope.chartData = [ { "label": "2017-05-11 16:00:00", "value": "930.6" } ...

The Angular Material nested Stepper's label position is being forcefully changed

When dealing with a nested Angular Material Stepper, the label position in the child stepper (labelPosition="end") may be overridden by the label position set in the parent stepper (labelPosition="bottom"). Check out the code snippet be ...

Icon for closing Mui Snackbar

I am facing an issue with my notification component that uses the mui snackbar to display alerts. I want to display multiple notifications stacked vertically, but when I try to close one notification using the "Close" icon, it ends up closing both that o ...

The API's post call is throwing an error, yet it functions perfectly when tested on

Currently, I have a functional Angular project that connects to real data using WebAPI2. However, I am now working on an Express.js project for demo purposes which mocks the data, providing random information instead of consuming the actual WebAPI2 data. T ...

Converting HTML to an array using Angular

Is there a way to convert HTML into an array of entities? For example: 'hi <em>there</em>' => ['hi', '<em>', 'there', '</em>'] ...

"Exploring the Power of Angular 2 with Route Resolving

Currently, I am diving into the world of Angular and it's all quite new to me. I have a challenge where I need to display data in a view fetched from the server asynchronously. To tackle this, I attempted to use resolves to ensure the data is retrieve ...

Upon launching Google Chrome, a series of errors plague the WSL2 Ubuntu setup while running Karma and Jasmine for Angular testing

My Angular project utilizes Google Chrome for testing with Karma & Jasmine, but upon starting Chrome, I encounter multiple errors. Despite trying various solutions found on Stack Overflow, none have been successful. The versions in use are: Chrome 99.0.4 ...

What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved. Here ...

Rearranging lists in JHipster: What is the best way to do it?

Seeking advice and guidance on implementing a drag-and-drop reorderable list in JHipster 6.7.1. To illustrate, picture creating a custom ordered list of objects where users can add, remove, and rearrange items. For instance, wanting to move [Epsilon] betw ...

Getting a "module not found" error in Next.js while trying to import a TypeScript

Check out this code snippet: // lib/customFunction.ts export function customFunction() { console.log("customFunction"); } // pages/homepage.tsx import { GetServerSideProps } from "next"; // works import { exampleFunction } from "../lib/exampleFile.js" ...

The malfunctioning collapse feature in Bootstrap 4 sidebar within an Angular 6 application

I am trying to find a way to collapse and reopen the sidebar when clicking on a button. I have attempted to create a function to achieve this, but unfortunately it did not work as expected. Important: I need to collapse the sidebar without relying on jque ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

What is the process of accessing the changelog.md file within a component in Angular?

My challenge is to showcase the content from my changelog.md file, which is situated at the same level as the package.json file. I created a service for this purpose using the following code, function getData() { return http.get('../c ...

From a series of arrays filled with objects, transform into a single array of objects

Upon using my zip operator, I am receiving the following output: [ [Obj1, Obj2, ...], [Obj1, Obj2, ...] ]. To achieve my desired result, I am currently utilizing the code snippet below: map(x => [...x[0], ...x[1]]) I am curious to know if there exists ...

Creating hierarchical TreeNode structure in TypeScript

As I work with a flat one-dimensional array of type TreeNode (view interface definition below), my goal is to recursively traverse the array and add subsequent array elements as children. While attempting a non-recursive approach using a buffer, I encount ...