Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this:

[{
    "Consumer": [{
        "Associated ID": "JSUDB2LXXX / BIC 7503 / US",
        "Parent Consumer": "7503"
    }],
    "Owner": [{
        "Entity": "EN",
        "Region": "LA"
    }]
}]

I am looking to transform it into the following format. Each old key and value pair will be split into a separate object with "title" as the new key for the old key, and "name" as the corresponding value.

[{
    "Consumer": [{
            "title": "Associated ID",
            "name": "JSUDB2LXXX / BIC 7503 / US"
        },
        {
            "title": "Parent Consumer",
            "name": "7503"
        }
    ],
    "Owner": [{
            "title": "Entity",
            "name": "EN"
        },
        {
            "title": "Region",
            "name": "LA"
        }
    ]
}]

Answer №1

Just a little something to assist:

let sampleData = [{
    "Customer": [{
        "ID": "JSUDB2LXXX / BIC 7503 / US",
        "Parent Customer": "7503"
    }],
    "Owner": [{
        "Organization": "EN",
        "Area": "LA"
    }]
}]

let result = []
sampleData.forEach(item => {
  Object.keys(item).forEach(propertyKey => {
    let valuesArray = []
    Object.entries(item[propertyKey][0]).forEach(entry => {
      valuesArray.push({heading: entry[0], content: entry[1]})
    })
    let newElement = {}
    newElement[propertyKey] = valuesArray
    final.push(newElement)
  })
})
console.log(result)

You can experiment with it here :

https://jsbin.com/wazuyoyidi/edit?js,console

Answer №2

Using a different approach.

const modifiedResults = data.map((level) => {
  const updatedObject = {};
  Object.entries(level).forEach(([key, value]) => {
    updatedObject[key] = value
      .map((item) =>
        Object.entries(item).map(([property, val]) => ({ property, val }))
      )
      .flat();
  });
  return updatedObject;
});

[https://jsbin.com/rafinobexa/edit?js,console][1]

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

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

Getting rid of quotes in a JSON result

My unique code snippet Retrieve data = Array[2] : 0:object id : "1" lat : "76.23" long:"21.92" 1:object id:"2" lat:"10.23" long:"12.92" var newCoords=[]; for(_i = 0; _i < ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

Exploring the technique of utilizing a custom completion block with JSONDecoder to efficiently parse nested JSON data

My goal is to extract image URLs from a nested JSON object and populate the collectionViewCell with them. I plan to iterate over the list.recommendBannerImages and store it in an external variable for use in my collectionViewCells. ...

Transform a section of text into JSON format to utilize in DataTables

Currently, I am utilizing DataTables and Leaflet in my project. The data displayed below needs to be represented on my screen using Datatables. Specifically, I would like to convert it into JSON format without including the {....} part. How should I proc ...

Tips for revealing a hidden HTML tag

I am currently trying to validate the content within #textd to ensure it is not empty and contains more than 150 characters. If it meets these conditions, I need to transfer the content to another webpage; otherwise, display an error message based on the c ...

Is it possible for GSON to perform deserialization in a case-insensitive manner?

While prototyping the communication between a .NET desktop app and a Java server using REST with JSON posts, a case-sensitivity issue has arisen. The .NET objects have their properties in Pascal Casing (as is standard for .NET), such as: Symbol, EntryValue ...

typescript error is not defined

While browsing online, I came across a post discussing how to transfer data from an MVC model to a .ts file. The suggestion was to include the following code: <script type="text/javascript"> var testUrl = @Html.Raw(Json.Encode(Model.testUrl) ...

Issues arise when trying to use JQuery in conjunction with JSON data

I've been working on a project that involves creating a dynamic dropdown list, but I've run into an issue with jQuery and JSON. This is my first time working with JSON, so I'm still getting the hang of it. Despite googling for solutions, I h ...

Having trouble with installing a React app using npx create-react-app my-app?

description needed for image Having trouble creating a react application using npx create-react-app my-app... Encountering errors shown in the image. Attempted npm init but it was unsuccessful. Included node.js and vs code in the path. ...

Using Javascript to fetch JSON data from a PHP file hosted on an IIS server, incorporating JSONP with

I have set up an HTML5, JavaScript, and CSS3 https application on Windows IIS (Internet Information Services). The structure of the root directory is as follows: index.html, src/index.js, src/send_payment.php Currently, I am attempting to retrieve a basi ...

Can anyone guide me on successfully converting SQL Server data to JSON format in real-time using ASP.NET and Visual Studio?

My main objective is to continuously export data from MS SQL server in real-time and convert it into JSON format. This JSON data will then be used to generate a dynamic line graph on the front end using AM Charts Dataloader. The goal is to keep the line gr ...

Can we display an express view in response to a WebSocket event?

My goal is to display an express view within a websocket event as shown below: socket.on('name', function () { //prompt the client to render a specific express view }); ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

Other options besides re-flowing and repainting

After doing some research on various platforms like Stack Overflow, I've come across information stating that re-paints and re-flows can be quite taxing on a browser's resources. I am interested in learning about alternative CSS/JS techniques to ...

Using JavaScript to Access PHP Files

Would like to understand the process of calling a php file (test.php) from either "x:" or "y:" in the code below. var example1 = { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], name: 'Most read', ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...

Error encountered during JSON deserialization process

My JavaScript function is named sendData. var sendData = function (data) { alert("The data being sent to the server"); var dataToSend = JSON.stringify(data); alert(dataToSend); $.ajax({ type: "POST", ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

Encountering an error in Angular where the property does not exist in type

Struggling to create a collapsible menu within my header component in an Angular project, I've hit a snag with proper JSON formatting. The error message that keeps popping up reads: Error: src/app/components/header/header.component.html:48:49 - error ...