What is the best way to combine an array of objects into a single object?

I have a set of objects that I want to convert into objects with specific key names, following the format {key}{index)

const input = [
    {
        item: 'Apple',
        amount: '3'
    },
    {
        item: 'Banana',
        amount: '5'
    },
    // ...
]

Here is an illustration of the expected output where each index gets added to the key name resulting in item1, amount1, item2, amount2..

const output = { item1: 'Apple', amount1: 3, item2: 'Banana', amount2: 5 }

Answer №1

Implement the use of reduce:

const updatedData = input.reduce((accumulator, element, position) => {
    let {itemData, itemQuantity} = element;
    
    // Adjusting for 0-based index by adding 1
    accumulator["itemData" + (position + 1)] = itemData;
    accumulator["itemQuantity" + (position + 1)] = itemQuantity;

    return accumulator;
}, {});

Answer №2

Give this a shot:


const transformedResult = input.reduce((acc, item, index) => {
        Object.keys(item)
        .forEach(key=>{
            acc[key+(index+1)] = item[key]
        })
    return 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

Obtain the currently selected HTML element using tinyMCE

Within my editor, I have the ability to choose text and show it using the code below: alert(tinyMCE.activeEditor.selection.getContent({format : "html"})); The problem is that this function only returns text and not HtmlElement. This means I am unable to ...

Create a PHP form that includes text and image inputs with the help of AdminLTE and integrates DropZone.js

I have been working with a template from adminLTE and you can check it out at the following link: . At this point, I am trying to upload images first and then use the image names as input text elements in my main form for submission. However, I have encou ...

Divide an HTML file into separate documents upon submitting a form

Is there a way to input HTML into a text area, then upon submission, have the system read the file, identify the class selector, and separate the HTML into multiple files saved in a directory? If you have any thoughts on how this could be accomplished, pl ...

Tips for determining if a player (canvas) is in contact with a drawn wall for collision detection

I created a 2D map using the canvas HTML element where I drew a red square to represent the player and a light blue wall underneath it. I am looking for a way to detect if the player (red square) is in contact with the wall (light blue). The elements do no ...

PHP/MySQL: Retrieving columns with unidentified names

I am facing an issue with a script that is retrieving rows of values from a MySQL database table and returning them as an array : $player_login_request = $db->query('SELECT * FROM Players'); while ($player_login = $player_login_request->fe ...

What is the best method for communicating between windows in an electron application?

As I embark on the journey of creating my first electron app, I kindly ask for your understanding :) Upon clicking a button in the main Window, a new window should open displaying a JSON string. This action is captured by ipcMain: ipcMain.on("JSON:ShowPa ...

Retrieving data from the chosen selection in AngularJS

My current task involves extracting the URL from the selected option and assigning it to the ng-model of the select element. Here is the HTML code snippet: <select ng-model="ddValue1.value"> <option ng-repeat="d in ddOptions1" value="{{d.val ...

iOS is not receiving JSON data in the response headers

I am currently utilizing the CocoaHTTPServer for establishing my server connection. However, I encountered an issue with retrieving JSON data in the header file of my HTML page (web client). Here is the code snippet : HTML Page : endAPSession: funct ...

Organizing identical array elements in PHP participants into groups

I created a function to detect word sequences: function checkSequence($arrScheme = [], $arrInput = []) { $sequenceNeeded = array_values(array_intersect($arrScheme, $arrInput)); if(!empty($arrInput) && ($sequenceNeeded == $arrIn ...

Nuxt - issue with updating window innerwidth getter

The class based components in our project utilize a getter to retrieve the window innerWidth. However, I've noticed that the value is only set once and doesn't update if the window width changes. get viewPortWidth() { if (process.client) { ...

The use of fixed values in defining arrays

The book "C++ Primer" states that According to the book, array dimensions must be known at compile time, requiring them to be constant expressions. It goes on to explain that unsigned count = 42; // not a constant expression constexpr unsign ...

The onclick function is malfunctioning when attempting to use the Windows Phone app in Visual Studio 2015

web development <div class="align_center"> <div class="btn EmployeeloginBtn" **onclick="new Employee().connect()**>CONNECT</div> </div> Employee.js: var Employee = function() { var self = this; self.connect = fu ...

CodeIgniter 4 Route Fails to Respond when a Different Value is Provided

I am currently engaged in self-studying Code Igniter 4. My focus is on inserting records irrespective of transactions. I have defined parameters such as Add, Edit and Delete. In the case of 'Add' being the passed value, a new record will be inser ...

Can the placement of Vue.js methods impact the overall performance and size of the application?

I am currently working with a list component and a looping item component structured as follows: RoomList.vue <template> <ul id="TheRoomList"> <button id="TheCreateRoomButton" @click="createRoom()& ...

This line of code is really confusing to me. Can you explain how accessing a member of a structure actually works?

#include<stdio.h> #include<conio.h> struct student { int enroll; char name[50]; }stu[2] = { {11, "Rj"}, {12, "Ay"} }; int main() { int en; printf("Enter Enroll: "); scanf("%d", &en); ...

A div element with the class name "draggable" is

One of my functions sends notifications to a page by prepending a main div with the notification. Here is the function: function displayNotification(notificationTitle, notificationContent, notificationColor, notificationSize) { console.log('Attem ...

Identify whether the page is being accessed through the Samsung stock browser or as an independent web application

Hey there! I am on a mission to determine whether my webpage is being accessed through Samsung's default browser or as a standalone web app saved on the homescreen. Unfortunately, the javascript codes I have come across only seem to work for Safari an ...

Implementing a specialized CSS handler for Node.JS

Currently, I have set up a Node.JS server for a new project at my workplace. As part of the project, I have created an optimizer function that removes unnecessary elements such as tabs, newlines, and comments from HTML, JavaScript, and CSS files. Strangel ...

What methods can Yahoo use to escape an iFrame without relying on JavaScript?

It's strange that even when I disable javascript, Yahoo still ends up breaking. Take a look at this scenario: How is it possible for them to achieve that? ...

Sending parameters to async.parallel in Node.js

My goal is to create a simple example that demonstrates the concept I have described. Below is my attempt at a minimal example, where I expect to see the following output: negative of 1 is -1 plus one of 2 is 3 Here is the code I've written: var asy ...