Transforming the elements within an array of objects into individual key-value pairs and then adding them to a fresh array

Hello, I am diving into the world of Typescript/Javascript and encountering some challenges when it comes to manipulating arrays of data. Please bear with me as I navigate through my learning curve.

Imagine having an array of objects structured like this:

items = [{header: "h1", value: "header 1 test"}, {header: "h2", value: "header 2 test"}]

My goal is to iterate through each object in the array, extract their values, and transform them into key:value pair objects. I aim to insert these transformed objects into a new array that should resemble the following:

myNewArray = [{"h1": "header 1 test"}, {"h2": "header 2 test"}]

Currently, I am working on an Angular project with TypeScript, but I am open to suggestions utilizing either Javascript or Typescript. Any modern techniques would be greatly appreciated.

Despite my attempts at using ES6 syntax like [element.header]: [element.value] to create a new array, I am still facing some challenges.

Thank you in advance for your help!

Answer №1

let elements = [{header: "h1", value: "header 1 test"}, {header: "h2", value: "header 2 test"}];

let transformedElements = elements.map(item => ({[item.header]: item.value}));
console.log(transformedElements);

Answer №2

To achieve this, you can utilize the map method on an array. Here is an example in code:

const transformedArray = items.map((item) => {
    const header = item.header;
    const value = item.value;

    return {
        [header]: value
    };
});

By using the map method, you iterate over each element in the array and apply the specified function to transform it. This results in a new array containing the transformed values grouped together.

Answer №3

One thing that might trip you up is the use of parentheses to enclose the object being returned in a map function

const data = [{heading: "h1", content: "content 1"}, {heading: "h2", content: "content 2"}]
.map(item => ({[item.heading]: item.content}))

console.log(data)

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

Generate slanted projection mapboxgl

Trying to develop a building simulator based on zoning codes. I can measure values, create floors, but struggling to extrude diagonally or create a perpendicular plane to the floor for evaluating angles from the street to limit building height (see image 2 ...

Array[object..] logical operators

I am currently working with Boolean and logical operators using code like this: Just so you know, I want to convert object values and logic into an array to perform logical operations. For example: object1.logic object.operators object2.logic as either tr ...

I updated the script to include a feature that automatically adds a leading zero to hours, minutes, and seconds if they are less than 10. However, for some reason, the output still doesn't show the leading zero

I have successfully created a countdown timer that works effectively. One of the conditions I added is to display leading zeros for hours, minutes, and seconds if they are less than 10. The desired format is like this (06 : 08 : 09) instead of (6 : 8 : 9 ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...

Filtering in AngularJS based on a specific ID

Currently, I am dealing with a JSON encoded response from PHP that looks like this... [ {"ID":"149","IDusr":"4","aut_more_info":"good","doc_name":"img1838142879.jpeg","doc_type":"jpg"},{"ID":"149","IDusr":"4","aut_more_info":"good","img5733250433.jpeg","d ...

How about a custom-designed talking JavaScript pop-up?

Looking to customize the appearance (CSS, buttons...) of a "confirm" JavaScript dialog box while ensuring it remains persistent. The dialog box appears after a countdown, so it is crucial that it maintains focus even if the user is on another browser tab o ...

Utilizing various layouts in ASP.NET MVC with AngularJS

I am setting up two different layouts, one for visitors and one for management. Routes: app.config(['$routeProvider', function ( $routeProvider) { $routeProvider .when('/', { templateUrl: 'Home ...

Vue: Opening all GmapInfoWindows simultaneously upon clicking one

I am working on a platform where users can report crimes or incidents by placing markers on a map. These markers with all the reported incidents are then displayed on another map. Each marker has an info window that provides details about the incident and ...

Instructions for updating the Modal Value using ajax

This is the script I use to retrieve the data <script> $(document).ready(function() { $('.tmpsurat').click(function() { var id=$(this).data('id'); var url ='{{URL('/cekSuratKelengkapan')}}/'+id; ...

My HTML gets rearranged by browsers, causing a change in appearance

UPDATE: I have discovered that the issue lies with Internet Explorer which alters the class attribute of an HTML element from: "<img class="blah".." to "<img class=blah..". This inconsistency only occurs in IE for me. It does not affect other attr ...

JavaScript does not reflect updates made to the ASP.Net session

After clicking the button, I trigger the JavaScript to retrieve the session information. However, I am encountering an issue where the value of the session is not being updated. alert('<%= Session["file"]%>'); ...

Postman is displaying [object object] as the return value, but the actual value is not

Currently, I am working on automating tasks using Postman One interesting aspect is the presence of a vehicles array in the body { "Vehicles":[ { "car":"{{car}}", "bike":"{{bike}}&quo ...

ServiceAccountKey cannot be located by Firebase deploy

I am in the process of integrating a serviceAccountKey into my Typescript cloud functions project. var serviceAccount = require("/Users/kareldebedts/myAppName/functions/serviceAccountKeyName.json"); admin.initializeApp({ storageBucket: "appName.appspot ...

The eccentricities of Angular Translate in Firefox and Safari

While everything functions correctly in Chrome, there seems to be an issue with changing the language in Safari and Firefox. angular.module('angularApp') .config(['$translateProvider', function ($translateProvider) { $translateProv ...

Restrictions on the number of characters based on the size of fonts in an html list sc

Recently, I attempted to implement a ticker message on my website using li scroller. However, it appears that there is a limitation on the number of characters that can be displayed in the ticker message when different font sizes are used. With a smaller ...

Generating PNG images with text using Node.js

I am currently working on generating a PNG file to be sent to clients through HTTP as an image/png response type. This new file will be created by combining 3 base PNG files and inserting custom text in the center of the image. Unfortunately, I have not ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...

Enhancing image search functionality through dynamic HTML updates

I need help figuring out how to update the link address for profile pictures on my NHL stats website. Currently, I am using a script to append the image to the body, but I don't know how to properly add the player ID ({{p1_ID}}) to the link and includ ...

Having trouble retrieving JSON with crossDomain jQuery AJAX

The process I followed was creating a rails 3.0 scaffold and exposing it using json, keeping it running. When accessing http://localhost:3001/objects.json I can view json data in the browser Next, I had a simple html file with code.jquery.com/jquery-1.7 ...

Unable to locate module within the ngModule imports

I am facing a peculiar issue. I have used npm install to add ng-push, imported PushNotificationsModule from 'ng-push', and included PushNotificationsModule in my ngModule imports. Interestingly, both the ng build and ng build --prod commands are ...