Creating a JSON object from an array of data using TypeScript

This might not be the most popular question, but I'm asking for educational purposes...

Here is my current setup:

data = {COLUMN1: "DATA1", COLUMN2: "DATA2", COLUMN3: "DATA3", ..., COLUMNn: "DATAn"};

keyColumns = ["COLUMN2", "COLUMN5", "COLUMN9"];

keyValueMap = {};

This is what I am aiming to achieve:

keyValueMap = {COLUMN2: "DATA2", COLUMN5: "DATA5", COLUMN9: "DATA9"};

Here's what I have attempted so far:

if (keyColumns.length > 0)
    {
      keyColumns.forEach(key => {
        keyValueMap[key] = data[key];

      });
    };

I understand that directly assigning values like keyvaluemap[a] = data[a] won't work since keyvaluemap is just an object. How can I structure this in a way that achieves my desired outcome of getting all value pairs? Also, keep in mind that the list of values in keyColumns is dynamic and cannot be predetermined.

Answer №1

If you want to utilize the .reduce() method of Arrays, here is how you can do it:

let info = {NAME: "John", AGE: 30, CITY: "New York", OCCUPATION: "Engineer"},
    importantKeys = ["AGE", "CITY"];

let customReducer = (infoObj, keys) => keys.reduce((accumulator, currentKey) => (accumulator[currentKey] = infoObj[currentKey], accumulator), {});

console.log(customReducer(info, importantKeys));

Answer №2

give this a shot:

const extractedData = keyColumns.reduce((acc, cur) => !!data[cur] ? ({...acc, [cur]: data[cur]}) : acc;
}, {});

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

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

Creating a dropdown menu for an extensive list of 100 menu items: a step-by-step guide

In my React JS front-end project, I have implemented a drop-down menu using Material-UI. Currently, the menu items are hardcoded which works fine for a small number of items. However, this approach becomes cumbersome when dealing with a larger number of ...

Can the caller function's arguments be altered using Function.prototype.apply()?

function modifyValues(a,b){ console.log(arguments); //["oldValue","oldValue"] var newArguments = updateValues.apply(this,arguments); for (var i=0;i<arguments.length;i++){ arguments[i] = newArguments[i]; } console.log(arguments); // ...

Animation effect in Jquery failing to execute properly within a Modal

I have developed a small jQuery script for displaying modals that is both simple and efficient. However, it seems to only work with the fadeIn and fadeOut animations, as the slideUp and slideDown animations are not functioning properly. I am unsure of the ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

Serialization of JSON arrays using Jackson in Java

I've encountered a unique scenario where I'm attempting to serialize data using Jackson. Here is an example of the payload: { "key1": [ [ 10, 11 ], [ 12, 13 ] ...

The script from '*' is being denied execution because its MIME type ('application/json') is not executable, and a strict MIME type check is in place

Here is the code I used to retrieve data from the confluence rest api: <script type="text/javascript" src="Scripts/jquery.min.js"></script> <script> $.ajax({ type: "GET", url: "https://blog.xxxxx.com/rest/api/content? ...

Neglecting to send a socket signal while assigning a variable to a socket message

In my client-side script, I am using the following snippet: socket.on('bla', function(data) { if (data == ID) { console.log('I don't understand what's happening here.'); } }) socket.on(ID, function(data) { ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

Using this PHP function

I am facing an issue with a table that contains some information. I want to be able to click on a specific row (e.g. the second row) and display all the corresponding database information. However, I am unsure how to achieve this using the $this function ...

Updating the Position of an Element in ElectronJS (e.g. Button, Label, etc)

Is there a way to change the positioning of a button in a window using JavaScript and Electron? I am trying to create new input boxes next to existing ones, but they always appear below the last one created. Is it possible to specify x and y coordinates fo ...

Tips for employing dependentRequired with relative references in JSON schema

I'm currently using the NewtonSoft JSON schema validation library to validate user JSON against a specific schema in my app. There are certain rules that need to be followed: If the user includes property2 in the JSON, then both property3 and subProp ...

Utilize a recursive function to incorporate data into an array nested within other arrays

I am facing an issue where the data I'm trying to add to an element containing nested arrays is not getting updated in MongoDB, even though it appears correctly in the console. I have developed a function to navigate through the entire structure of th ...

Error: Model attribute missing in Adonis JS v5 relationship

Recently, I started diving into the Adonis framework (v5) and decided to build a todo list api as part of my learning process. However, I'm facing an issue concerning the relationship between the User and Todo entities. Let me show you the models fo ...

Executing a webservice method in an html page using javascript without the need to refresh the page

Is it possible to call a webservice from an index.html page using JavaScript? My webservice is located at "localhost/ws/service.asmx" and the specific web method I want to call is called HelloWorld. The index.html page contains an HTML submit button whic ...

Displaying a certain div when clicked within a loop using Vue.js and Laravel

I am currently facing an issue with displaying a hidden div upon click. The problem arises when using a loop to dynamically generate all the divs. Whenever I click the button, it shows all the divs instead of just one specific div on each click. I attempte ...

Enhance your coding experience with Angular Apollo Codegen providing intelligent suggestions for anonymous objects

Currently, I am exploring the integration of GraphQL with Angular. So far, I have been able to scaffold the schema successfully using the @graphql-codegen package. The services generated are functional in querying the database. However, I've noticed ...

A recursive function that utilizes a for loop is implemented

I am encountering a critical issue with a recursive function. Here is the code snippet of my recursive function: iterateJson(data, jsonData, returnedSelf) { var obj = { "name": data.groupName, "size": 4350, "type": data.groupType }; if ...

This function has a Cyclomatic Complexity of 11, exceeding the authorized limit of 10

if ((['ALL', ''].includes(this.accountnumber.value) ? true : ele.accountnumber === this.accountnumber.value) && (['ALL', ''].includes(this.description.value) ? true : ele.description === this.description.valu ...

Converting a base64 string to a PNG format for uploading to an S3 bucket from the frontend

Feeling a bit overwhelmed here, hoping this isn't just a repeat issue. I've come across similar problems but none of the solutions seem to be working for me at the moment. I'm currently utilizing react-signature-canvas for allowing users to ...