How can I transform a string array into an object array using Angular 2?

If I have an array like this:

categories = ['Fruit', 'Vegetable', 'Grain'];

I want to transform it into an array of objects with the following structure:

[
    {
        id: 1,
        type: 'Fruit'
    },
    {
        id: 2,
        type: 'Vegetable'
    },
    {
        id: 3,
        type: 'Grain'
    }
]

Answer №1

You have the option to utilize the map function to loop through the original array and generate new objects.

let categories = ['Vintage', 'Modern', 'Classic'];

let items = categories.map((value, index) => {
  return {
    id: index + 1,
    type: value
  };
})

To see a live demonstration, click here.

Answer №2

If you're looking for a solution to the problem mentioned above, consider utilizing the map() method available in JavaScript or Type Script.

The map() method is designed to create a new array by executing a provided function on each element within the original array.

let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
/*The map() method creates a new array by running 
a designated function on every element of the array.*/

     let types = [
         'Old',
         'New',
         'Template'
        ];


  /*
    let newArray = arr.map((currentvalue,index,array)=>{
         return Element of array
     });
  */


   let Obj = types.map((value, i) => {
         let data = {
                 id: i + 1,
                 name: value
             };

      return data;
    });

    console.log("Obj", Obj);
</coede></pre>

<p>For more information, explore the following links:</p>

<p><a href="https://www.typescriptlang.org/play/index.html#src=%2F*map()%20method%20creates%20a%20new%20array%20with%20the%20results%20of%20calling%20%0D%0Aa%20provided%20function%20on%20every%20element%20in%20the%20calling%20array.*%2F%0D%0A%0D%0Alet%20types%20%3D%20%5B0D%0A%20%20%20%20'Old'%2C%0D%0A%20%20%20%20'New'%2C%0D%0A%20%20%20%20'Template'%0D%0A%5D%3B%0D%0A%0D%0A%0D%0A%2F*%0D%0Alet%20newArray%20%3D%20arr.map((currentvalue%2Cindex%2Carray)%3D%3E%7B%0D%0A%20%20%20%20return%20Element%20of%20array%0D%0A%7D)%0D%0A*%2F%0D%0Alet%20Obj%20%3D%20types.map((value%2C%20i)%20%3D%3E%20%7B%0D%0A%20%20%20%20let%20data%20%3D%20%7B%0D%0AM%20Iteration%203%ECeph%205+10Mm%2C%29a%20-%7Baata%0D%0ASqqninja->%3Bo%eRturn%07es+-+SRretu+aZa+%27%", +14%0DqwYt60nUr78o5+88.tools68+"eaTaBL56.data34%>;
TypeScript</a></p>

<p><a href="https://jsfiddle.net/vsvaibhav2016/kqc1m25p/" rel="nofollow noreferrer">JS-Fiddle</a></p>

<blockquote>
  <p>To tackle the aforementioned problem, we can also utilize a for loop :</p>
</blockquote>

<pre><code>let types = [
    "One",
    "Two",
    "Three"
];

let arr = [];

for (let i = 0; i < types.length; i++){
    let data = {
        id: i + 1,
        moana: types444[i]
    };
    num4.push(data);
}

console478.36('data', exy);

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

Pattern to identify digits from 0 to 9 along with specific symbols

I am currently in the process of creating a regular expression that can match 0 to 9 (up to 10 digits) and /-. (0 to 2 max), without having to be all . or all //. It can be /.\- or .-. or any combination of the three, with a maximum of two of those ch ...

Is there a way to reposition a popup window to the center of the page after launching it?

popup = window.open(thelink,'Facebook Share','resizable=1,status=0,location=0, width=500,height=300'); My goal is to perfectly center this popup window both vertically and horizontally. ...

Best Practices for Handling Pre-State Setting Mutations in Flux Design Pattern

Currently, I am developing a Vue application utilizing Vuex and following the Flux design pattern. I have encountered what seems to be an inefficient practice of duplicating code in small increments. I am hopeful that this is just a misunderstanding on my ...

Maximizing the Potential of SWR with Any Type

I've created a custom hook that wraps around SWR: import useSWR from 'swr'; export enum MethodTypes { POST = 'POST', PUT = 'PUT', GET = 'GET', DELETE = 'DELETE', PATCH = 'PATCH' } ...

Is there a way to obtain the tasklist result of exec() from child_process and convert it to JSON format?

When I use the tasklist command with child_process, the stdout returns processes in Unicode string format that is not easily queryable. Here is the code snippet: var exec = require('child_process').exec; ... exec('tasklist', function( ...

Issue encountered while attempting to save a value in localStorage

I am encountering an issue while trying to save and read the value of a button in the panel. The error message I receive is - Unable to set property 'adl' of undefined or null reference. This is my first time working with localStorage, so I' ...

Filter out the truthy values in an array with JavaScript

I am currently working with a javascript array called 'foo' which looks like this: var foo = [false,false,true,false,true]; My goal is to eliminate all the 'true' values and only keep the 'false' ones, resulting in this arra ...

Mastering Props Typing in React Using TypeScript

Currently, I am faced with the task of defining the following: interface MyCompProps { someAttr: number } Instead of having to explicitly list all the aria-* attributes I need upfront, I would like to simply use aria- and other normal HTML attributes ...

Can a JavaScript function spontaneously run without being called upon?

<a onclick="determineCountry(data)" class="installbtn">Install</a> My goal is to have the user redirected to one of three sites based on their location when they click the button above. However, there seems to be an issue with the script below ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Is there another way to implement this method without having to convert snapshotChanges() into a promise?

When trying to retrieve cartIdFire, it is returning as undefined since the snapshot method is returning an observable. Is there a way to get cartIdFire without converting the snapshot method into a promise? Any workaround for this situation? private asyn ...

Dealing with field errors on ajax forms in CakePHP

CakePHP offers a fantastic Error Validation feature where all errors are automatically displayed next to each field in the view. It works flawlessly. However, things get tricky when trying to implement this with Ajax. Is there a way to streamline this pro ...

What steps can be taken to add a radio button group to a form in order to choose between the smoking and non-smoking sections of a restaurant?

I'm trying to replicate the functionality of radio buttons within a bootstrap form-group, where a line in a form contains multiple buttons ("btn btn-success" for example) that can be selected, but only one at a time. I am aiming for an output like thi ...

Issue with assigning Type (Date|number)[][] to Array<,Array<,string|number>> in Angular with typescript and google charts

Currently, I am utilizing Angular 8 along with the Google Charts module. My latest endeavor involved creating a Google Calendar Chart to complement some existing Google charts within my project. However, upon passing the data in my component.html file, I ...

Guide on launching a Firefox browser through Selenium 3.6.0 with a different profile in JavaScript

How can I customize the Firefox browser settings in selenium-webdriver 3.6.0 for automated testing? I need Firefox to download files without prompting and save them to a specific directory. For Google Chrome, the approach is as follows: if (this.bName == ...

What could be the reason why the links within my drop-down menu are not directing me to other pages?

As I work on developing a new website, I have encountered an issue with the content inside my dropdown button not being engaging enough. Specifically, I have a link within a dropdown button located in the footer (visible on mobile), but this link does not ...

Display options in Material-UI autocomplete only upon clicking the icon

Is there a way to display the options list only when clicking on the arrow icon as opposed to the textfield itself? I have reviewed the documentations without success in finding a solution. Example ...

Guide on how to transform form data into an object containing nested properties

Considering the inputs provided below: <input name="person[1]['first']" /> <input name="person[2]['first']" /> <input name="person[3]['first']" /> The objective is to convert this into an object structure a ...

Unable to set a background image sourced from API data onto a div element in Node.js

I am having trouble setting a background image to a div using the API-provided link in my CSS. Even when trying to directly access the image in Chrome, nothing seems to happen. Here's the code snippet: function getData(responseData) { var poster ...

How can Protractor find elements using non-HTML custom attributes?

When running e2e tests on my Angular project using Selenium WebDriver and Protractor, I encountered an issue with locating elements that have custom attributes. For example, I have an element like: <div my-directive my-unique-id="abc123"></div> ...