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

Accessing Ionic rootScope within the config stateprovider - A step-by-step guide

Is it possible to access the value of $rootScope in the following line? .config(function($stateProvider, $urlRouterProvider) { $stateProvider // I am trying to retrieve the value of $rootScope here. } ...

a solution to the focus/blur issue in Firefox's browser bug

I have created the following script to validate if a value entered in an input field already exists in the database. $('#nome_field').blur(function(){ var field_name=$('#nome_field').val(); $.ajax({ url: " ...

By default, the text area element in Vue or Nuxt will send a message to the console

Every time I include a textarea html element in my Vue/cli or Nuxt projects, this message appears in the console. Is there a way to prevent this message from showing up in the console? <textarea rows="5" cols="33"> This is a textarea. < ...

adding a new div to the bottom of a row that is being created on the fly

I encountered an issue where rows are created dynamically and I needed to add a div at the end of each row. Despite trying various methods, I faced difficulties as adding the div resulted in extra divs being added to all previous rows whenever a new row wa ...

Is there a way to compel the browser or JavaScript to delete/disregard a cached file?

I've encountered an issue with my Javascript program that extracts data from a text file and displays it in a table. The problem arises when I update the text file - the changes don't reflect on the table because the browser is caching the file. ...

Animated CSS sidemenu (utilized as a filtering panel for a table)

Hi there, I'm having some trouble with CSS Animation. I recently started developing websites and am using Bootstrap 4 along with Animate.css for animations. My goal is to have an icon button expand sideways to reveal a div containing select elements f ...

Combine several dictionary values under a single dictionary key in JavaScript

I have a unique dictionary structure displayed below. My goal is to populate it with values in a specific way. It all begins here var animals = { flying : {}, underground : {}, aquatic : {}, desert : {} }; To illustrat ...

How to retrieve the class of a dynamic div by clicking on a different div using jQuery?

I am trying to retrieve the class of a dynamic div when clicking on another div with the class name "div.secondclass". Below is my code snippet: $(document).ready(function() { $("div.secondclass").click(function () { firstclass=$('#firsti ...

Transform a JSON string into a JSONArray

As I attempt to generate test data using a JSON String, the process encounters an issue when attempting to convert the string into a JSONArray resulting in a failed test. String JSONString = "{\"Info\":[{\"area\":301336,\"nati ...

Modify the events JSON URL when the Full Calendar changes its display period

Whenever I switch between months or weeks, I need the JSON URL link to update accordingly. For example: The initial JSON URL is: /json/?start=2018-01-28&end=2018-03-10 When moving to the next month, the URL changes to: /json/?start=2018-02-25&am ...

VueJS error: Trying to access properties of undefined object ('$refs') is unsuccessful

Parent Component: ... <v-stepper-step :rules="[()=>isValid(1)]" > MyStep </v-stepper-step> <v-stepper-content> <Mytag ref="MyReference" /> </v-stepper-content> ... methods: { isValid(number){ ...

Using C# to generate a JSON array by extracting information from a CSV file

I am trying to generate JSON data in C# by pulling information from a CSV file. The desired JSON structure is shown below: { "car":[ { "manufacturer": "Nissan", "fuelType": "p ...

Unable to arrange an array of JavaScript objects retrieved via an Angular REST request

I'm currently encountering an unusual issue with sorting an array of JavaScript objects. While sorting some dummy data works fine, I am unable to sort the array when fetching the object through an Angular REST call. The structure of the message is as ...

Is there a secure way to prevent user input from causing issues in a BigQuery node insert? Can the BigQuery.insert node library support parameterized queries for added security

I am seeking advice on how to securely insert user form data into BigQuery using the Google Cloud BigQuery library. Specifically, I am curious about the most effective methods for sanitizing, escaping, and cleaning the input data. Is it feasible to implem ...

Struggling with slow loading times for Three.JS GLTF models? Discover ways to optimize and speed up the load time

My GLTF model (9mb) is loading slowly in ThreeJS. It takes about 4-5 seconds to load on my PC and around 11 seconds on my iPhone. I'm looking for ways to speed up the rendering times. Surprisingly, examples from the ThreeJS website load faster than my ...

methods for transferring javascript variables to modal

<div> <h5> <a href="<?php echo base_url(); ?>/vendor/home/projects" >Return to Projects</a> </h5> <div> <div class="container"> <div class="row"> ...

Can someone tell me what comes after my nextElementSibling in this specific scenario?

I am puzzled by the usage of nextElementSibling in this code. Can someone provide an explanation on what exactly it is and where it should be used? Thank you in advance! Also, my code seems to be malfunctioning as I keep receiving an error message that s ...

error encountered while parsing nlohmann json at memory location

Currently working on a C++ program that aims to fetch information from multiple pages of an API endpoint and store it in an array. Utilizing cpr as the requests library for fetching pages accurately, followed by nlohmann's json library for parsing and ...

What is the best method to collect information from multiple AJAX requests?

In addition to synchronous AJAX calls, what is the most effective approach for handling a situation like this? var A = getDataFromServerWithAJAXCall(whatever); var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A); var C = getMoreDataFromServe ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...