Combine values from 2 distinct arrays nested within an array of objects and present them as a unified array

In my current array, the structure looks like this:

const books[{
    name: 'book1',
    id: '1',
    fromStatus: [{
        name: 'Available',
        id: 1
    }, {
        name: 'Free',
        id: 2
    }],
    toStatus: [{
        name: 'Not available',
        id: 1
    }, {
        name: 'Not free',
        id: 2
    }]
}, {
    name: 'book2',
    id: '2',
    fromStatus: [{
        name: 'Burnt',
        id: 1
    }],
    toStatus: [{
        name: 'Not burnt',
        id: 1
    }]
}]

I am looking to create a new array with the following structure:

const statusFromTo[{
    {
        id: 1,
        fromStatusName: 'Available',
        toStatusName: 'Not available'
    },
    {
        id: 2,
        fromStatusName: 'Burnt',
        toStatusName: 'Not burnt'
    },
    {
        id: 3,
        fromStatusName: 'Free',
        toStatusName: 'Not free'
    },
}]

The matching of from and to statuses is based on their respective ids. For instance, Free and Not Free both have an id of 3, Available and Not Available both have an id of 1, Burnt and Not Burnt both have an id of 2.

I've attempted different forEach and .map methods but haven't been successful so far. Any suggestions or help would be appreciated! I am using TypeScript for this task.

Answer №1

Check out this (Playground link):

const books = [{
    name: 'book1',
    id: '1',  
    fromStatus: [
        { name: 'Available', id: 1 },
        { name: 'Free', id: 2 }      
    ],
    toStatus: [
       { name: 'Not available', id: 1 },   
       { name: 'Not free', id: 2 }
    ]
}, 
{
    name: 'book2',
    id: '2',
    fromStatus: [
        { name: 'Burnt', id: 1 }
    ],
    toStatus: [     
        { name: 'Not burnt', id: 1 }
    ]
}]

const statusFromTo = books.map(b => b.fromStatus.map((fromStatus, i) => ([fromStatus.name, b.toStatus[i].name])))
    .reduce((prev, curr) => [...prev, ...curr], [])
    .map(([fromStatus, toStatus], id) => ({id, fromStatus, toStatus}))

console.log(statusFromTo)

While this code assumes certain conditions about the structure of the data (such as same length and matching IDs), it generates a unique statusFromTo array based on the provided example.

  • If there are variations in the arrays' lengths or item orders based on their IDs, adjustments may be necessary for accurate results.

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

How can I merge these two Observables in Angular to create an array of objects?

Let's say we are working with two different datasets: student$ = from([ {id: 1, name: "Alex"}, {id: 2, name: "Marry"}, ]) address$ = from([ {id: 1, location: "Chicago", sid: 1}, {id: 2, location: &qu ...

What is the best way to initiate a refetch when the need arises to follow a different path?

I have encountered a situation where I am able to pass the refetch function on a child component. However, an issue arises when transitioning to another page and implementing redux. This is particularly problematic when attempting to open a dialog for a ne ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

Is there a method for verifying the application signature in Ionic?

For the past 2 days, I've been on a quest to find information about app certificate validation libraries/functions in Ionic. After discovering SignatureCheck.java for Android (link: enter link description here), I wonder if there is a similar solution ...

When working with TypeScript in Node, the module ""http"" does not have a default export available

const httpModule = require('http'); httpModule.createServer((req, res) => { res.end('Hello World'); }).listen(3000, () => console.log('Server is running on port 3000')); I've installed @types/node but ...

Form submission returns JSON data with an undefined value from the server

I've been following a tutorial here but ran into some issues due to using newer versions of Angular and Ionic. This is an excerpt from my code: createReview(review){ let headers = new HttpHeaders(); headers.append('Content-Type&apo ...

What is the best way to implement record updates in a nodejs CRUD application using prisma, express, and typescript?

Seeking to establish a basic API in node js using express and prisma. The schema includes the following model for clients: model Clients { id String @id @default(uuid()) email String @unique name String address String t ...

Within Angular, the Subscribe function is invoked after all other methods in the component have been executed. Consequently, this sequence of events often prevents me from effectively utilizing the response data

Struggling with implementing await and async in TypeScript, especially as a beginner. Below is how I attempted to use them: async refreshList(){ await this.service.refreshList().subscribe(res => { console.log(res); this.service.todoListModel=res; ...

Angular: issue with form validation - password matching is not functioning as expected

I have successfully implemented the registration form with basic validations The code I used can be found in: registration.html <form #registrationForm="ngForm" (ngSubmit)="onFormSubmit()"> ... <div class="form- ...

Setting the base path for npm tests: A step-by-step guide

I am currently working on a web application that utilizes Angular as the front-end technology and Java Spring Boot as the backend. https://i.sstatic.net/IWPNZ.png In the screenshot above, you can see that I have created a new directory within the root fo ...

Can anyone guide me on implementing getServerSideProps in a TypeScript NextPage component?

I've come across a page that I'd like to replicate, with the code sourced from https://github.com/dabit3/nextjs-lit-token-gating/blob/main/pages/protected.js: import Cookies from 'cookies' import LitJsSdk from 'lit-js-sdk' ex ...

When a React component in TypeScript is passed as a parameter and then assigned to a variable, an error with code TS2604 may occur stating that the JSX element type does not

I am currently facing an issue with handling props of a passed React Element in my Factory. I am getting a TypeScript error that says: TS2604: JSX element type 'this.extraBlock' does not have any construct or call signatures. This is my Child co ...

The absence of defined exports in TypeScript has presented a challenge, despite attempting various improvement methods

I've exhausted all available resources on the web regarding the TypeScript export issues, but none seem to resolve the problem. Watching a tutorial on YouTube, the presenter faced no such obstacles as I am encountering now. After updating the tsconf ...

How to check Internet upload speed in Angular without using a backend server?

I need help uploading a file to a folder within my Angular app's directory while it is running on localhost. I have been unable to find a solution that doesn't involve using backend technologies. For instance, I simply want to upload an image fi ...

Instructions on how to present a list of employee information according to the user's gender preference using a selection of three radio buttons

I have developed a view that displays a table of employees, using a json array to store their details in the component. Additionally, I have implemented 3 radio buttons: all, male, and female. My goal is to have the table show all employees when "all" is ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

How can I exclude the 'node_modules' directory but still include specific subfiles in the tsconfig file for TypeScript?

My tsconfig file is structured as follows: { "compileOnSave": false, "compilerOptions": { "module": "es2015", "target": "es2015", "sourceMap": true, "jsx": "react", "allowSyntheticDefaultImports": true, "noImplicitAny": false, ...

Failed to execute start script 'ng serve' in npm start

Let me make it clear: I'm brand new to AngularJS and pretty much any Web Technology. I consider myself a novice in the realm of Web Development. I attempted to install AngularJS, and truth be told, after numerous "Mysterious Button Clicks", I might ...

Error in Typescript: The 'type' property is not found in the 'string' type

I am working on creating a React component that includes subcomponents within it. I came across this insightful article that has been guiding me through the process. The concept is to design a Modal component with distinct sections such as Modal.Header, M ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...