Transform the collection of nested objects into an array of objects with identical key-value pairs and then output the result after each iteration

My goal is to transform an object with objects inside into an array of objects. The initial data looks like this:

  "data" :{ 
    "tDetails": {
      "tName": "Limited",
      "tPay": "xyz"
    },
    "bDetails": {
      "bName": "name",
      "bid": "bid",
      "bNo": "123456"
    },
    "iDetails": {
      "iName": "iname",
      "iBranch": "ibranch"
    }
}

The objective is to convert it into an array of objects, iterating over the three headers (tDetails, iDetails, bDetails) as follows:

  const newData =  [
    {
      "id": 1,
      "title": "tDetails",
      "content": [
        {
          "id": 1,
          "key": "tName",
          "value": "Limited"
        },
        {
          "id": 2,
          "key": "tPay",
          "value": "xyz"
        }
      ]
    },
    {
      "id": 2,
      "title": "bDetails",
      "content": [
        {
          "id": 1,
          "key": "bid",
          "value": "12345"
        }
      ]
    },
    {
      "id": 3,
      "title": "iDetails",
      "content": [
        {
          "id": 1,
          "key": "iName",
          "value": "iname"
        },{
          "id":2,
          "key": "iBranch",
          "value": "ibranch"
        }
      ]
    }
   
  ]
  const NewData = () => {
    let newDetails = [];
    let newHeader = '';
    for (const header in data) {
      // header here is 'tDetails', bDetails, iDetails 
      const headerData = data[header]; 
      newDetails = Object.entries(headerData).map(([key, value]) => ({
        key,
        value,
      }));
      newHeader = header;
    }
    return [
      {
        title: newHeader,
        content: newDetails,
      }
    ];
  };

Currently, only the last part of the data (iDetails) is returned due to the for loop. What changes should be made to fix this issue?

Answer №1

Instead of using for..in, try mapping the object's entries and return the transformed object in the callback function.

const data={tDetails:{tName:"Limited",tPay:" xyz"},bDetails:{bName:"name",bid:"bid",bNo:"123456"},iDetails:{iName:"iname",iBranch:"ibranch"}};

const newData = Object.entries(data).map(([title, obj], i) => ({
  title,
  id: i + 1,
  content: Object.entries(obj).map(([key, value], j) => ({
    id: j + 1,
    key,
    value
  }))
}));
console.log(newData);

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

What could be causing my randomly generated value to be overwritten so quickly?

I'm encountering an issue with my code. I am attempting to generate objects in random locations using drawHyperBall(), getRandomIntX(), and getRandomIntY(). However, the random value seems to be constantly overwritten. How can I resolve this problem? ...

Change the hover effects on the desktop to be more mobile-friendly

In my desktop version, I have implemented some code that enables hovering over a button to display additional information or text. How can I modify this for mobile so that nothing happens when the button is tapped on? .credit:hover .credit-text, .credit- ...

Streamlining JSON nested array queries in Postgres for optimal performance

I am facing a challenge while attempting to query a JSON data structure in Postgres (9.6 on Amazon RDS). The dataset consists of an array of objects, and within them, there is an element containing another array of objects. My goal is to identify all entri ...

Identifying flex-wrap capabilities across different browsers

Currently, I am developing a project that involves implementing a responsive grid using the flex wrap property. However, since my project needs to support IE9 and older versions of Firefox (version 28 and below), I am in need of a way to determine their ...

`Assemble: Store the newly created Stripe "Client Identity" in a designated container`

Upon a new user registration on my website, I aim to create a Stripe customer ID along with username and email for database storage. The process of customer creation seems to be working as evidenced by the activity in the Stripe test dashboard. However, h ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

Tips on how to engage in a spontaneous audio experience

I am currently developing a Discord bot with the intention of having it play a random mp3 file upon joining a voice channel. case"join": message.delete( {timeout: 5000}) const voiceChannel = message.member.voice.channel ...

Choosing a String and Performing a Double Click in Selenium with Java

My textbox is disabled, and it includes the following attributes: <div id="writingactivityId2" class="boxSize ng-pristine ng-untouched ng-valid ng-valid-required redactor_editor writingActivityDisabled" ng-focus="editing()" redactor="" readonly="" ng- ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

The Jqueryui image link is not displaying the image despite no error being reported

Can anyone help me figure out what I'm missing? I'm currently working with ASP.NET MVC 5 and have downloaded the JqueryUI combined via Nuget package. Despite no error references for css/js files, the close button is still not showing in the ima ...

Converting JavaScript functions to Java remote method interfaces

Experience: A while back, I was involved in developing a Java Server-Client application for building automation purposes. Initially, we used Java RMI to connect the server and client but soon realized that utilizing JavaScript for the client side would be ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Troubles encountered when attempting to use Axios to call a third-party API in a React JS application

Challenge Description: I set out to create a dropdown menu of post-offices based on the user-entered pincode. To achieve this, I utilized an API and Axios for the backend request. While I successfully populate the dropdown with the necessary data, the is ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Tips for verifying if two passwords match during registration and displaying an error message if they do not match

How can I ensure that the passwords entered in a registration form match and how do I validate the entire form to be correct? <form id="registerForm" method="POST" action="/register" class="form2"> ...

Turn off and then reinstall Image when clicked

function show(){ alert("i am pixel"); } function disableImgClick(){ $(".Dicon").unbind('click'); } $(document).ready(function(){ $("#turnoff_btn").click(function (e){ e.preventDefault(); disableImgClick(); }); }); i have a group of ima ...

Python - Converting JSON data into a CSV file

I need help with a script that reads JSON data from a file and then extracts specific content to populate a table. The challenge I'm facing is that the structure of the JSON data varies for different entries, making it difficult to map the fields accu ...

What are the steps to apply an AngularJS filter for formatting values within an array?

While I have experience using angular filters for formatting primitive values like numbers into currency formats, I am now faced with the challenge of applying the same filtering to an array of values. For example: price = 1 prices = [1,2,3] If I were to ...

Execute asynchronous functions without pausing the thread using the await keyword

When working with an express route, I need to track a user's database access without: waiting for the process to complete before executing the user's task worrying about whether the logging operation was successful or not I'm uncertain if ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...