Combining Arrays of Items in Typescript

I am dealing with an array in Angular 14 that looks like this:

[
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Color",
        "oldValue": "Rainbow",
        "newValue": "Rainbow1"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Pg #",
        "oldValue": "4",
        "newValue": "44"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Status",
        "oldValue": "New",
        "newValue": "Rev"
    }
]

I am seeking help to convert the data into a different format. I want to change the column values to be the property name, like this:

{
"parentItem": "WBP258R",
"childItem": "WBP258R",
"Color": "Rainbow",
"Color_newValue": "Rainbow1",
"Pg #": "4",
"Pg #"_newValue": "44",
"Status":"New",
"Status_newValue": "Rev",
}

If anyone can provide assistance, it would be greatly appreciated. Thank you in advance.

Answer №1

To achieve this goal, utilizing Array.reduce() would be a suitable approach.

[
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Color",
        "oldValue": "Rainbow",
        "newValue": "Rainbow1"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Pg #",
        "oldValue": "4",
        "newValue": "44"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Status",
        "oldValue": "New",
        "newValue": "Rev"
    }
].reduce((acc, val) => {
    if(!acc['parentItem']){
        acc['parentItem'] = val['parentItem'];
        acc['childItem'] = val['childItem'];
    }
    acc[val['columnName']] = val['oldValue'];
    acc[`${val['columnName']}_newValue`] = val['newValue'];
    return acc;    
}, {})

Answer №2

const dataArr = [
    {
        "itemParent": "WBP258R",
        "itemChild": "WBP258R",
        "dataColumn": "Color",
        "priorValue": "Rainbow",
        "newVal": "Rainbow1"
    },
    {
        "itemParent": "WBP258R",
        "itemChild": "WBP258R",
        "dataColumn": "Pg #",
        "priorValue": "4",
        "newVal": "44"
    },
    {
        "itemParent": "WBP258R",
        "itemChild": "WBP258R",
        "dataColumn": "Status",
        "priorValue": "New",
        "newVal": "Rev"
    }
];

function modifyData(arr) {
    const resultObj = {};

    arr.forEach(entry => {
        const colName = entry.dataColumn;
        const key = colName.replace(/\s+/g, ''); // Eliminate spaces in property names
        resultObj[key] = entry.priorValue;
        resultObj[`${key}_newVal`] = entry.newVal;
    });

    resultObj.itemParent = arr[0].itemParent; // Include non-column attributes
    resultObj.itemChild = arr[0].itemChild; // Include non-column attributes

    return resultObj;
}

const finalOutput = modifyData(dataArr);

console.log(finalOutput);

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

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

I am unable to update an array within my component using useEffect

Encountered two problems, firstly while attempting to pass an array of objects from a parent component to a child component, facing difficulties as shown below: function DropdownSome ({options, placeholder, someNum}) { const [value, setValue] = useState ...

What Key Information Am I Overlooking in Analyzing this JSON Data?

Having trouble parsing JSON output with Python and need some assistance. Here is the JSON data: { "start": 0, "terms": [ "process_name:egagent.exe" ], "highlights": [], "total_results": 448, "filtered": {}, "facets": {}, "results": ...

The attribute 'getTime' is not found in the data type 'number | Date'

class SW { private startTime: number | Date private endTime: number | Date constructor() { this.startTime = 0, this.endTime = 0 } start() { this.startTime = new Date(); } stop() { this.endTim ...

"Tips for retrieving properties from a JSON object that has been converted to a string

I'm facing an issue with retrieving the url from a response in my code. The goal is to use this url for navigation using the router function. Here's the problematic code snippet: const redirectToStripe = async () => { const response = await ...

Sending the value from a for loop through AJAX and populating it into a form field

Currently, I have implemented a piece of JavaScript code that captures user input, sends a request to an endpoint using AJAX, and appends a specific field from the returned results as an option within a datalist. This functionality is working perfectly fin ...

Nested interfaces can utilize sum types

An example showcasing the use of sum types: interface Cash { amount: number, type: 'cash' } interface Card { amount: number, type: 'card', cardNumber: string } type Payment = Cash | Card const displayPayment = (payment: Pay ...

Each time input is entered, the JSON data is duplicated and the entered input is not visible on the screen

As I delve into learning Next.js, my goal is to create a basic todo list using a JSON todos API for data. In the process of building the program, I opted to utilize Redux Toolkit for fetching the todos data. However, I am encountering an issue where newly ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

Checking the integrity of JSON information

Currently in my AJAX requests, I am manually validating each JSON entry by using the "key" in json.some_location.keys() method repeatedly. Is there a more efficient way to accomplish this, such as XML validation? Additionally, I am open to using validatio ...

I am curious about creating a 3D scatter plot using a 3D array. Each marker's size in the plot is determined by the value within the array. Can anyone

Having some trouble with my code for creating a 3D array and plotting it in the Spyder IDE. Here's the code snippet: import numpy as np import math as m import matplotlib.pyplot as plt a = 3 b = 4 c = 2 d = 0 if a > b and a > c: d = a i ...

Parsing PHP JSON data into variables

I'm facing an issue with my JSON data. I am sending it through C# and receiving it on my PHP MySQL server. Normally, I catch the data using POST method but now I realize I should use json_decode instead. Even though I can see and print out the data, I ...

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

Having trouble launching the node pm2 process manager on AWS Elastic Beanstalk, npm update verification did not pass

Having some issues with utilizing pm2 for managing processes in my typescript node application, deployed on elasticbeanstalk. Whenever a new instance is launched by pm2, the following shows up in the logs ---------------------node.js logs---------------- ...

Using JSON Schema to validate multiple occurrences of a property

I'm currently working on defining a JSON schema that includes multiple properties for instances of the same object in a Java application endpoint. For instance, here is a simple example of what I'm aiming to accomplish: { "$schema": "http://jso ...

Gathering user key event input for a duration of 2 seconds before resetting it

I need help implementing a feature where I can clear the user's input text after 500ms if they are entering characters consecutively. private userInputTimer; private userInputText = ''; private handleEvent(event: KeyboardEvent): void { if ...

Encountering unspecified values when subscribing to a BehaviorSubject and receiving it as an Observable

My goal is to display the name of the currently logged-in user in the header of my application. However, I encountered an issue where upon refreshing the page, the value would be lost due to SPA behavior (even though the data is stored in local storage). T ...

Discovering the ways to declare an array type in Haskell

Creating a linked-list type in functional languages like Haskell is straightforward, as shown by the simple definition: data List a = Nil | Cons a (List a) However, I have not come across any tutorials that explain how to define your own array type from ...

Using TypeScript with Vue to Retrieve Information from a Form

Currently, I am attempting to retrieve data from a form in Vue using TypeScript. However, when declaring the data that I intend to use with this form, it seems to be posted on the fields as shown in this screenshot: message getting posted. I am unsure ho ...

How can I retrieve Piwik JSON data and incorporate it into a chart.js visualization?

I am using the piwik PHP API to generate data like this: [ {"label":"1680x1050","nb_visits":9,"nb_actions":53,"max_actions":27,"sum_visit_length":3051,"bounce_count":3,"nb_visits_converted":0,"sum_daily_nb_uniq_visitors":7,"sum_daily_nb_users":0,"segme ...