Converting objects to arrays in reactJS

Here is the object structure I currently have:

    {
      DepositAmt_0: 133
      DepositAmt_1: 455
      DepositAmt_2: 123
      DepositNotes_0: "some notes "
      DepositNotes_1: "some comment"
      DepositNotes_2: "some comment"
      PayReference_0: "aaa"
      PayReference_1: "bbb"
      PayReference_2: "qwerty"
      PaymentType_0: "payment"
      PaymentType_1: "card"
      PaymentType_2: "card"
}

This object is being received when the form is submitted.

I need a way to transform this object into the following format:

    [
    0:{DepositAmt:123, DepositNotes:"some notes", PayReference : "aaa", PaymentType:"payment"},
    1:{DepositAmt:455, DepositNotes:"some comment", PayReference : "bbb", PaymentType:"card"},
    2:{DepositAmt:123, DepositNotes:"some comment", PayReference : "qwerty", PaymentType:"card"},
    ]

Answer №1

If you are looking to manipulate a list of object keys, consider using the .reduce() method:

// Create an initial object
const input = {
      DepositAmt_0: 133,
      DepositAmt_1: 455,
      DepositAmt_2: 123,
      DepositNotes_0: "some notes ",
      DepositNotes_1: "some comment",
      DepositNotes_2: "some comment",
      PayReference_0: "aaa",
      PayReference_1: "bbb",
      PayReference_2: "qwerty",
      PaymentType_0: "payment",
      PaymentType_1: "card",
      PaymentType_2: "card",
}

// Use reduce on 'input' keys
const result = Object.keys(input).reduce((acc, el) => {
  // Split each key into name and index
  const [name, index] = el.split('_');

  // Assign key to element with its corresponding index
  if (!acc[index]) acc[index] = {};
  acc[index][name] = input[el];
  return acc;
}, {});

// The result now contains indexes as keys 
// and desired elements as values
console.log(Object.values(result));

Answer №2

This is a possible solution

const details = {
  Amount1: 200,
  Amount2: 500,
  Amount3: 150,
  Note1: "some remarks",
  Note2: "additional info",
  Note3: "important notes",
  Reference1: "1234",
  Reference2: "5678",
  Reference3: "91011",
  Type1: "credit",
  Type2: "debit",
  Type3: "transfer",
}

const {
  attributes,
  highest
} = Object.keys(details).reduce((result, item) => {
  const [attribute, index] = item.split('_')
  return {
    attributes: [...new Set([...result.attributes, attribute])],
    highest: Math.max(result.highest, index)
  }
}, {
  attributes: [],
  highest: 0
})
const finalResult = Array(highest + 1).fill(0).map((_, index) =>{
  return attributes.reduce((res, attr) => {
    return {
      ...res,
      [attr]: details[attr + '_' + index]
    }
  }, {})
  }
)
console.log(finalResult)

Answer №3

Here is a method to simplify the object:

const obj = {
  DepositAmt_0: 133,
  DepositAmt_1: 455,
  DepositAmt_2: 123,
  DepositNotes_0: "some notes ",
  DepositNotes_1: "some comment",
  DepositNotes_2: "some comment",
  PayReference_0: "aaa",
  PayReference_1: "bbb",
  PayReference_2: "qwerty",
  PaymentType_0: "payment",
  PaymentType_1: "card",
  PaymentType_2: "card"
};

const transformObject = (object) => {
  const objKeys = Object.keys(object);
  const result = objKeys.reduce((resultObject, currentProperty) => {
    const propertyNumber = currentProperty.slice(-1);
    const newPropertyKey = currentProperty.substring(0, currentProperty.length - 2);

    return {
      ...resultObject,
      [propertyNumber]: {
        ...resultObject[propertyNumber],
        [newPropertyKey]: object[currentProperty]
      },
    };
  }, {});

  return result;
};

console.log(transformObject(obj));

// 0: { DepositAmt: 123, DepositNotes: "some notes", PayReference: "aaa", PaymentType:"payment" },
// 1: { DepositAmt: 455, DepositNotes: "some comment", PayReference: "bbb", PaymentType:"card" },
// 2: { DepositAmt: 123, DepositNotes: "some comment", PayReference: "qwerty", PaymentType:"card" },

Answer №4

Below is a handy function I quickly put together to assist you:

const data = {
  DepositAmount_0: 200,
  DepositAmount_1: 350,
  DepositAmount_2: 100,
  Notes_0: "important notes",
  Notes_1: "additional comments",
  Notes_2: "feedback",
  Reference_0: "xyz",
  Reference_1: "abc",
  Reference_2: "12345",
  Type_0: "online transfer",
  Type_1: "cash",
  Type_2: "credit card",
};

const transformDataToArray = (input) => {
  const resultArr = [];

  for (const [key, value] of Object.entries(input)) {
    const keyInfo = key.split("_");
    const index = parseInt(keyInfo[1]);
    if (resultArr[index] === undefined) {
      resultArr.splice(index, 0, {});
    }
    let newObj = resultArr[index];
    newObj = { ...newObj, [key]: value };
    resultArr[index] = newObj;
  }

  return resultArr;
};

console.log(transformDataToArray(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

Issue: Incorrectly calling a hook. Hooks can only be used within the body of a function component. Assistance needed to resolve this issue

import React, { useState } from "react"; const RegistrationForm = () => { const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(" ...

Exploring the Functionality of ngMousedown and ngMouseup in AngularJS

Is it viable to apply ngMousedown to add a class to a div, and then use ngMouseup to remove the class once more? Currently, I am utilizing ng-mousedown="activateClass()". Within the activateClass() function, I modify $scope.className="data-active", which i ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefine ...

Is it possible to iterate over an enum using Object.entries<T>(Enum).map() in TypeScript, or does it only function with string-based enums?

Currently, I am in the process of developing a react form that requires users to select options related to a job. These options are represented by enums, with some being string-based and others number-based. For instance, here is an example of a string-ba ...

Managing actions on dynamically generated dropdown options in <select> elements

If I have a function that generates a dropdown, it is called from a parent component where props like state key, array, and onChange function are passed in. The dropdown items are dynamically created from the array. What I want is for the parent's sta ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

Trying to understand the strange behavior of HTML parsing with jQuery in Javascript and Firefox

I have been working on a script to parse an HTML page using jQuery. The script runs smoothly in Chrome, IE, and Safari, but I'm facing some unexpected behavior while testing it in Firefox (version 36.0.1). Here's the code snippet: $.ajax({ u ...

Error message: JavaScript is unable to save data to an array retrieved from Ajax, resulting in

I am facing an issue with retrieving continuous data from the database using AJAX and storing it in a JavaScript variable. Despite my efforts, I am unable to populate an array with the retrieved values as they always end up being undefined. Below are the s ...

Page elements subtly move when reloading in Chrome

I am experiencing an issue with a div that has left and top offsets randomly selected from an array of values upon page load. Most of the time, it works fine. However, occasionally, upon refreshing the page, the window scrolls down slightly, revealing the ...

"Utilize a specific parameter in the npm run script for enhanced

Is it possible to pass a named parameter to an npm run script in order to achieve the following functionality? "scripts":{ "say-hello":"echo $greeting && ls" } npm run hello --greeting=hello The desired outcome is to replace the $greeting ...

Updating a nested document within an array - Utilizing MongoDB with the Node.js driver

I am struggling to achieve the following task: locate a document with a specific id, then find the corresponding document in the legacy array based on a shortID, and update the sets array of that matched embedded document. For some reason, I can't se ...

What is the best way to import scss files and images in Vue.js storybook stories?

In this component, I am importing an image using src="@/assets/images/logo.png" with the help of @ for addressing: <template> <div class="loading_container"> <img class="loading_logo" src="@/assets/ ...

What is causing my vue.js table to not display properly?

Struggling to render a table using vue.js? You're not alone. Many developers face challenges when trying to use v-for to iterate through data and display it in a table format. It can be frustrating when everything seems fine in the console, but the ta ...

Is it possible to transfer .NET backend functions to a frontend framework like React or Vue for client-side execution?

For instance, imagine a scenario where there is a login page requiring a username and password to meet specific criteria for validation: the username must contain a capital 'A' and the password should be exactly 8 characters long. The challenge l ...

Issue with the submission button not triggering onclick event correctly

I've been trying to add an onclick event to a submit button. I've searched various tutorial sites and followed all the suggestions, but none of them have solved the issue. Interestingly, when I include an alert in the function being called, it wo ...

What is the best way to incorporate user-provided values into a dynamic URL?

I am trying to create a feature where users can input a value and then click a button that will take them to a URL tailored to their entry. Here is my current code, but I am facing an issue - the user_input data does not seem to be passed to the URL when ...

Incorporating Javascript into a .Net MVC 3 Project

It seems like there should be a straightforward solution to my question, but I'm struggling with it. I have an animation.js file that includes dependency_1.js and dependency_2.js in an include folder. Within my animation.js file, I load these dependen ...

Changing the value within a deeply nested object

I am facing an issue with a nested object in my code: { id: "id", name: "Name", type: "SC", allgemein: { charname: "Name", spieler: "Jon", }, eigenschaften: { lebenspunkte: "30", }, talente: {}, zauber ...

What methods can I use to identify my current page location and update it on my navigation bar accordingly?

My latest project involves a fixed sidebar navigation with 3 divs designed to resemble dots, each corresponding to a different section of my webpage. These sections are set to occupy the full height of the viewport. Now, I'm facing the challenge of de ...