typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows.

export interface Basicdata {
    materialnumber: number;
    type: string;
    materialclass: string;
}

We also have an array containing values that correspond directly to the Basicdata model in order, like this:

["10003084", "S", "CLIP"]

I am exploring ways to create an object using these array values. One approach is to initialize an empty object and populate it with the array values.

const singleRow = rows[0];

const newBD: Basicdata = {
 materialnumber: 0,
 type: '',
 materialclass: '',  
}


newBD.materialnumber = singleRow[0];
newBD.type = singleRow[1];
newBD.materialclass = singleRow[2];

However, I believe there must be a more elegant solution to accomplish this. I have tried to use map and reduce but haven't found a suitable method yet.

Any suggestions would be appreciated.

Answer №1

Implementing a class is suggested by others to utilize the spread operator efficiently (alternatively, you could create a function that returns an object adhering to the Basicdata interface)

class Basicdata {
  materialnumber: number;
  type: string;
  materialclass: string;

  constructor(materialnumber: string | number, type: string, materialclass: string, ...rest: any) {
    this.materialnumber = typeof materialnumber === "number" ? materialnumber : parseInt(materialnumber);
    this.type = type;
    this.materialclass = materialclass;
  }
}

const rows: [string, string, string][] = [
  ["10003084", "S", "CLIP"],
  ["4324324", "B", "FOUR"],
  ["4444432", "C", "CORN"],
];

const singleRow = rows[0];

const newBD = new Basicdata(...singleRow) ;

Playground link

Answer №2

An issue with the method presented here is its reliance on the consistent order of object properties. Is this in line with what you are seeking?

const rowValues = [1, "2", "3"];

const newObj: NewObject = {
    number: 0,
    type: "",
    category: "",
};

Object.keys(newObj).map((key, index) => {
    newObj[key] = rowValues[index]
});

If this does not meet your requirements, you may consider creating a class as suggested by others or utilize a helper function like below to assist with your specific scenario.

const createProperties = (values) => {
    const updatedObj = {
        number: values[0],
        type: values[1],
        category: values[2],
    };

    return updatedObj
};

createProperties(rowValues)

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

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

Troubleshooting: Issues with locating CSS and JS files (404 error) while utilizing URL parameters within Django platform

I've designed a dashboard page that showcases various graphs. The page automatically updates the graph data every hour. You can access the page at the following URL: http://localhost/dashboard I'd like to give users the option to specify the ...

Having trouble sending posts to an API route with Angular's HTTP module

When attempting to send values via a POST request in the URL of an Angular5 Laravel API route, I encountered an issue. Despite not receiving any errors in the browser console, no network activity was recorded upon sending the request. It is perplexing as I ...

There is an issue showing up in the console: $(…).datepicker is not defined as a function

I am new to using HTML with JavaScript. I attempted to implement a datepicker, but unfortunately, it is not working as expected. The error message I am receiving is '$(...).datepicker is not a function' in the console. I am utilizing multiple f ...

Bootstrap relies on jQuery for its JavaScript functionality, so jQuery must be loaded before using Bootstrap's JavaScript

I encountered an issue while trying to load the Bootstrap library, consistently receiving this error message: Uncaught Error: Bootstrap's JavaScript requires jQuery Even though I have ensured that jQuery is loaded before attaching the Bootstrap li ...

Run ajax function prior to changing location; status now marked as canceled

Imagine needing to redirect a page when a button is clicked: <div onClick="clickButton"></div> function clickButton(href) { // an HTTP post request is sent here, without a callback or then/done function sendSomeRequest() location.href ...

Setting the default typing language in Protractor: A step-by-step guide

Is there a way to specify a default typing language in my configuration file? While running test cases locally, I am unable to switch keyboard languages during execution as it impacts the typing language for Protractor causing the tests to fail. If you h ...

What steps should I follow to include a message in the custom form validation rule in my React application?

I'm currently developing a chat application using React 18 and Firebase 9. For cleaner form validation, I have integrated the Simple Body Validator. Within the Register form, there's an input field of type file for uploading user avatars. The ...

Enhance your coding experience with Firebase Autocomplete on VScode

Recently, I installed VScode along with the necessary packages for JavaScript development. As I started writing code involving Firebase, I noticed that the autocomplete feature, which worked perfectly fine in Xcode, was not functioning in VScode. How can I ...

Stop jQuery function from activating twice during scrolling

I'm looking for a solution to optimize my code that detects if an element is in the viewport and triggers certain actions. Currently, it re-runs the code every time a scroll event occurs when the element is above the fold. Is there a way to make it on ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

The issue with Jquery .post function not functioning properly within a popup div

After spending countless hours on this issue, I feel like I'm at a loss... The problem lies in a div that pops up with a button, where the button fills data into different sections of the HTML... Everything works fine except for when I use ajax to c ...

Determine if the browser displays <select multiple> as a modal dialog

Is it possible to use JavaScript to detect whether a specific browser displays a focused <select multiple> element as a popup or strictly as an inline box? On certain platforms, like the Android Browser and iOS Safari, the appearance of a popup can ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

Creating a dynamic anchor scrolling effect within a dropdown select menu

Having trouble achieving smooth scrolling with a select option element, only works with a link. Any suggestions? Check out the jsfiddle demo to see what I mean! $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location. ...

Error: Cannot access the length property of an undefined value in the JEST test

I'm currently working on incorporating jest tests into my project, but I encountered an error when running the test. The issue seems to be related to a missing length method in the code that I am attempting to test. It appears to be originating from s ...

What sets apart the utilization of add versus finalize in rxjs?

It appears that both of these code snippets achieve the same outcome: Add this.test$.pipe(take(1)).subscribe().add(() => console.log('added')); Finalize this.test$.pipe(take(1), finalize(() => console.log('finalized'))).sub ...

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...

Send data from an AJAX request to a Laravel controller

Here is the code for my ajax request where I am trying to pass values to a controller in Laravel. var deviceid="<?php echo $id; ?>"; var day="<?php echo $day; ?>"; $.ajax({ 'async': false, 'global': false, url ...

The absence of a defined window - react-draft-wysiwyg integration with Next.js (SSR) is causing issues

Currently, I am in the process of developing a rich text editor that is used to convert plain HTML into editor content using Next.js for SSR. While working on this project, I encountered an error stating "window is not defined," prompting me to search for ...