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

Unable to decipher JSON

Hello, I am trying to fetch JSON data which looks like this: "items":[ { "date_for":"2018-11-11", "fajr":"5:28 am", "shurooq":"6:37 am", "dhuhr":"11:52 am", "asr":"2:40 pm", "maghrib":"5:06 pm", "isha":"6:15 pm" ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Integrate a scrollbar seamlessly while maintaining the website's responsiveness

I encountered an issue where I couldn't add a scrollbar while maintaining a responsive page layout. In order to include a scrollbar in my datatables, I found the code snippet: "scrollY": "200px" However, this code sets the table size to 200 pixels r ...

Utilizing Typescript to ensure property keys within a class are valid

Looking for advice to make a method more generic. Trying to pass Child class property keys as arguments to the Super.method and have Child[key] be of a Sub class. class Parent { method<T extends keyof this>(keys: T[]){ } } class Child extends P ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...

Dealing with Placeholder Problems in Angular 2 Material when Using setValue

Encountering an issue with Angular2's material components when a component is updated via setValue. Check out the plnkr link below for more details... [unique PLNKR link] Observed that both the value and the placeholder are occupying the same space. ...

Expanding the outer div with Jquery's append() function to accommodate the inner div elements perfectly

I am facing an issue where my outer div does not expand automatically to fit the elements I append inside it using jQuery. The structure of my div is as follows: <div class="well" id='expand'> <div class="container"> < ...

The interface 'Response<ResBody>' has been incorrectly extended by the interface 'Response'

I am currently working with typescript and express in a node.js environment. Whenever I compile my code, I encounter the following bug: node_modules/@types/express-serve-static-core/index.d.ts:505:18 - error TS2430: Interface 'Response<ResBody>& ...

Is it acceptable to include a @types library as a regular dependency in the package.json file of a Typescript library?

Should the library also be compatible with Typescript projects? I am developing a Typescript library that utilizes node-fetch and @types/node-fetch, which will be shared through an internal NPM registry within the company. If I only include @types/node-f ...

Exploring JSON Parsing in Play2 and Scala without Defining a Data Type

{ "people": [ { "name": "Jack", "age": 15 }, { "name": "Tony", "age": 23 }, { "name": "Mike", "age": 19 } ] } I have a JSON data structure with information about people that I need to travers ...

Encountering a RuntimeError during the integration of Angular Js in Rails with ExecJS

Currently, I'm working on integrating Angular Js into a Rails Project and I've been following the tutorial provided at . However, after completing all the steps, I encountered the following error: https://i.sstatic.net/ehYCb.png I've searc ...

Concurrent Array Manipulation in C++

Currently, I am tackling an assignment that involves working with an input file to be inserted into a parallel array. The positive outcome is that there are no syntax errors, but unfortunately, some baffling logical errors have made their way into my work. ...

Alignment of the table with a fixed header and scrollable body

Currently, I am experiencing an issue with aligning a table. My aim is to have a fixed header and a scrollable body for the table. To do this, I have aligned the table header and body using: display: table-header-group For the table body, I have applied ...

Showcasing or concealing.JSON data depending on the selected item in a React and MaterialUI application

Looking to enhance the user experience, I am developing a dynamic FAQ section sourced from a JSON file containing an array of objects with 'Question' and 'Answer'. https://i.stack.imgur.com/mljpm.png The functionality is such that click ...

Code has been loaded successfully for react-loadable Chunks, however it has not been

Encountering a problem while trying to implement chunks in my React app using react-loadable Everything functions perfectly on webpack-dev-server in development mode. However, when I build the project and deploy it to the server, async components are ...

What is the best method for initializing the value of ng-model as an empty string in AngularJS?

I need help setting the initial value for an attribute in my model. Here's the code I'm using: <input type="text" ng-model="selectedModel.title" name="title" value="" > What I want is for the attribute value to be initially set as an empt ...

Displaying array data without the need for a loop in Vue.js and Axios

I want to display data in my Vue.js 3 app without using a loop. Here is the response from my Axios API: In My Axios Api I got reponse: [{id: 2, name: "sub_title", value: "The Best Developer Team", created_at: null, updated_at: null},… ...

Develop a directive for transforming data

In my latest project, I am looking to develop a LoaderDirective that can fetch an observable, display a spinner while loading the data, and then switch to showing the actual data once loaded. I also want it to expose the loaded data using the 'as&apos ...

React Native tutorial: Changing button color on press

When a user clicks on the TouchableOpacity element, I want to change the color of the button from the default gray to blue. Initially, the 'checked={this.state.newProjects}' newProjects variable is not present in the state, so when clicked it sho ...

Declaration in Typescript for an array of strings that will be returned as a

I am facing an issue with my async function that is supposed to return either a single string or an array of strings. Here is the relevant code snippet: async getAllAnnotationTimes(): Promise<string> | Promise<string[]> { return aw ...