Transform Object Data into Another Object Using Specific Model in Typescript

After receiving an array of objects from an API, I face the following structure:

Array [
  Object {
    "OPTIONNUMBER": "1",
    "OPTIONVALUE": "Here is your name ",
  },
  Object {
    "OPTIONNUMBER": "2",
    "OPTIONVALUE": "Footer",
  },
  Object {
    "OPTIONNUMBER": "3",
    "OPTIONVALUE": "https://google.com",
  },
]

I am looking for a way to map this data to an object with specific key-value pairs as [OPTIONNAME]: OPTIONVALUE;

The corresponding model has the shape:

export interface IOptions {
  opt1NAME: string;
  opt2FOOTER_TEXT: string;
  opt3LINK: string;
}

The desired output should resemble:

const options = {
  opt1NAME: 'Here is your name';
  opt2FOOTER_TEXT: 'Footer';
  opt3LINK: 'https://google.com';
}

I have tried using map and assign methods but struggled with properly mapping the object names.

edit1:

//appOptions here is an array of string that contains names
let options = {};
for (let i = 0; i < appOptions.length; i++) {
      Object.assign(options, {[appOptions[i]]:arr[i].OPTIONVALUE });
    }

This approach successfully creates the desired object, but lacks proper typing.

Answer №1

give this a try


const preferences = [];
const pref = ["pref1Title","pref2DESCRIPTION_TEXT","pref3URL_LINK"]
// add all your preferences in pref and it should work
for (let counter = 0; counter < y.length; counter+=3) {
    const preference:{[key:string]:any} = {};
    // y represents the data from your backend
    const items = y.slice(counter,counter+3);
    items.forEach((item,idx)=>{
        preference[pref[idx]]=item.PREFERENCEVALUE
    })
    preferences.push(preference)    
}

Answer №2

To address the issue, a strategy was devised to generate a blank object with no content (which would be utilized for context regardless):

export const initOptions: IOptions = {
  opt01FOOTER: '',
  opt02FOOTER_TEXT: '',
  opt03LINK: '',
}

Subsequently, in the function where restructuring is necessary:

let options: IOptions = initOptions;
const keys = Object.keys(options) as Array<keyof IOptions>;

//arr refers to the array containing names and values
for (let i = 0; i < arr.length; i++) {
  //Utilizing Object.assign() is suitable in this scenario
  options[keys[i]] = arr[i].OPTIONVALUE;
}

This setup now allows for convenient usage of options with descriptive identifiers:

console.log(options.opt02FOOTER_TEXT);

In case the number of options grows, simply including an additional entry to the model and an empty key-value pair to the initOptions is necessary.

I had explored options to work around generating an empty object and remain receptive to more effective solutions involving typed options.

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 process of transmitting a multidimensional array from JavaScript to PHP

Utilizing $.ajax for transmitting form values to a PHP script. In PHP, the form input fields are interpreted as arrays. However, I am unsure how to accomplish the same with JavaScript and jQuery in order to deliver them in a manner that PHP can interpret ...

obtain information from a Java servlet on a web page

I am working on a webpage that displays various coordinates (longitude, latitude), and I need to create a Java class to sort these coordinates. My plan is to send the coordinates to a Java servlet before displaying them on the webpage. The servlet will th ...

What is the typical number of open CLI terminals for a regular workflow?

After experimenting with Gulp, Bower, ExpressJS, and Jade, I have settled on a workflow that I am eager to switch to. The only issue I am facing is the need to have two terminals open simultaneously in order to use this workflow efficiently. One terminal ...

ReactJS - When a click event is attached to a list of elements, it triggers the "click" event for each individual element in the list

I have a group of li elements under a ul element (as shown below), and when I click on any li element, I want it to add a class name to just that specific li element. However, currently when I click on one li element, the click event is triggered for all l ...

using javascript to access the window's global variables from another window

After opening a new window from a webpage using window.open(url);, I've defined some global variables in the original window. I am now trying to figure out how to access these variables in the newly opened window. Does anyone have a solution for this ...

The requested resource does not have the 'Access-Control-Allow-Origin' header, resulting in a 401 error

I've been working on integrating spell check functionality using the Bing Spell Check API, but I've run into a 401 error. The specific error message is: The requested resource does not have an 'Access-Control-Allow-Origin' header. This ...

Choosing between radio buttons either horizontally or vertically within a table

Here is the markup I am working with: <table> <tr> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></ ...

Using GULP and NODE, what is the best way to retrieve the Jenkins BUILD_NUMBER in JavaScript?

I am having an issue with my gulp task named getBuildNumber. This task utilizes the Child Process module to run a script. gulp.task('getBuildNumber', function() { var buildNumber = child_process.execSync("echo $BUILD_NUMBER").toString(). ...

How can I make my Background change on click using hexadecimal color codes?

I am struggling with changing the background color of an html document using a button click. While colors like "yellow, "blue", and "red" work perfectly, I encounter an issue when trying to use hexadecimal colors such as "#000000". The if-condition doesn ...

Difficulty using Container, Row, and Col components in React-Bootstrap

Currently, I am diving into the world of React and React-Bootstrap to expand my skill set. My focus is on utilizing the React-Bootstrap grid layout effectively. However, I suspect that I might be doing something wrong in my implementation. It seems like t ...

Angular and Jest combo has encountered an issue resolving all parameters for the AppComponent. What could be causing this error?

I am currently working within a Typescript Monorepo and I wish to integrate an Angular 8 frontend along with Jest testing into the Monorepo. However, I am facing some challenges. The tools I am using are: Angular CLI: 8.3.5 My Approach I plan to use ...

What are the steps for launching nuxt js in a live environment without hot reloading?

When it comes to Nuxt.js, the rebuilding process after deployment can be a bit peculiar. It seems that once the website is rebuilt, it becomes unavailable for several minutes. I'm currently exploring options on how to run this process in the backgroun ...

Interact with an external JavaScript function using a button within a web application

I have a JavaScript file called dmreboot_service.js in my /js folder. By running this file with the command node /js/dmreboot_service.js, it successfully triggers a direct method in Azure. My goal is to be able to run this function or file when a button o ...

Executing Knex promises sequentially within a for loop

I have recently started to dive into Node and asynchronous coding, but I am struggling with a fundamental concept. I am trying to seed a database using knex, reading data from a CSV file and iterating through the rows in a for loop. In each iteration, I ne ...

Implementing TypeScript type definitions for decorator middleware strategies

Node middlewares across various frameworks are something I am currently pondering. These middlewares typically enhance a request or response object by adding properties that can be utilized by subsequent registered middlewares. However, a disadvantage of ...

Unable to process form submission using Ajax in ASP.NET MVC

I'm having trouble with submitting a form using ajax and opening a modal dialog after the ajax function is successful. Whenever I click the submit button, the process doesn't complete. Where could the issue be, in the ajax method or somewhere el ...

Sharing data between parent and child components in React

I am facing an issue with passing a dynamically generated value from child components to my parent/web component. The buttons in the child component are assigned a `value="URL"` based on MongoDB data, and I want to pass that value to my parent component us ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

What causes the React Query cache to be cleared upon page reload?

Hi there, I am new to Next.js and React Query. I would really appreciate any help or advice. I apologize for any mistakes in my English language skills. Currently, I am using Next.js v12 and React Query v3, along with the React Query DevTools. On one of ...

Determine data types for functions in individual files when using ElysiaJS

Currently, I am utilizing ElysiaJS to establish an API. The code can be found in the following open-source repository here. In my setup, there are three essential files: auth.routes.ts, auth.handlers.ts, and auth.dto.ts. The routes file contains the path, ...