Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript.

Current JSON:

{
  "furniture": {
    "matter": [
      {
        "matter1": "Matter 1 value"
      },
      {
        "matter2": "Matter 2 value"
      },
      {
        "matter3": "Matter 3 value"
      }
    ],
    "suspense": [
      {
        "suspense1": "suspense 1 value"
      },
      {
        "suspense2": "suspense 2 value"
      }
    ],
    "Direct": [
      {
        "System": "System value"
      }
    ],
    "Road": [
      {
        "Road key 1 ": "Road value "
      }
    ]
  }
}

Expected JSON:

{
  "furniture": {
    "matter": {
      "matter1": "Matter 1 value",
      "matter2": "Matter 2 value",
      "matter3": "Matter 3 value"
    },
    "suspense": {
      "suspense1": "suspense 1 value",
      "suspense2": "suspense 2 value"
    },
    "Direct": {
      "System": "System value"
    },
    "Road": {
      "Road key 1 ": "Road value "
    }
  }
}

Note: The "furniture" key is static in the code above. All other keys and values are dynamically generated.

Answer №1

If you're searching for arrays, consider constructing a combined object or flattening the nested levels.

const
    process = obj => Object.fromEntries(Object
        .entries(obj)
        .map(([key, value]) => [key, Array.isArray(value)
            ? Object.assign({}, ...value)
            : value && typeof value === 'object' ? process(value) : value
        ])),
    data = { furniture: { elements: [{ element1: "Element 1 value" }, { element2: "Element 2 value" }, { element3: "Element 3 value" }], mystery: [{ mystery1: "Mystery 1 value" }, { mystery2: "Mystery 2 value" }], Direct: [{ Channel: "Channel value" }], Path: [{ "Path key 1 ": "Path value " }] }, Variety: { "Steering System": "Hydraulic" } },
    finalResult = process(data);

console.log(finalResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Give this a shot

let items = {};
for (const key in jsonData.items) {
  let newObject = {};
  jsonData.items[key].forEach((item) => {
    for (const prop in item) {
      newObject[prop] = item[prop];
    }
    items[key] = newObject;
  });
}

let updatedData = { items: items };

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

Having trouble establishing a connection with Db2 while using protractor

Encountering an issue when attempting to establish a connection with a remote DB2 database, resulting in the following exception: SQL30081N A communication error has been detected. The communication protocol in use is 'TCP/IP'. The com ...

Can the root directory of a node module be customized or specified?

When publishing a node module with source files in a src directory, users typically need to specify the full path from the module when importing a file into their project. For example: Directory Structure: my-module --src ----index.js ----something-else ...

Different applications of data streaming apart from multimedia content

Exploring the various applications of streaming, particularly when sending data from a server to a visual client such as a web browser or an application, has sparked my curiosity. While I grasp the fundamental idea of transmitting data in chunks rather t ...

Django fixtures can be used for translating texts

I have an initial_data.json file with a column 'name' that I want to store in Django for translations. How can I make sure that when this value is printed elsewhere, it uses the translated version? Any suggestions would be greatly appreciated. Th ...

Apply a dynamic function to assign a background color to a specific class

Currently, I have a function called getBackground(items) that returns a background color from a JSON file list. Within my application, there is a component that automatically adds a class name (.item-radio-checked) when a user clicks on an item in the list ...

Tips for implementing looping while making predictions with a text classification model in Keras

I am a beginner with keras and have created a text classification model. When I test the model with one input, I get accurate predictions: text=["Cancelling insurance cover that is in excess of your needs"] one_test = tokenize.texts_to_matrix(text) text_a ...

When attempting to call a class in Node.js with Express, the return value is coming back

I am relatively new to working with Node.js and the Express framework. I am attempting to pass a value to a JavaScript class in order to process a query and make a call to the database, expecting to receive a result array. Here is the code snippet I am cur ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

Tips for removing null or empty values from a JSON string

I have a certain Model that looks like this: public class DataClass { public string Name { get; set; } public string Address { get; set; } public string ContactNo { get; set; } } Attempting to convert it into a Json request using the followin ...

Having a single quote within a double quote can cause issues with JavaScript code

I am currently developing a Django web app and facing an issue with sending a JSON object to my JavaScript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "te ...

The system encountered an issue: "Property 'add' is not defined and cannot be read."

I'm facing a dilemma with my exercise. Despite the numerous inquiries regarding this problem, I haven't been able to find a solution. I am hopeful that you can provide some assistance! Below is the code snippet in question: let myDivs = docume ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

Issue with AJAX request on Internet Explorer versions 8 and 9

This script is functioning properly in Internet Explorer 10 and above, as well as Chrome and other browsers. However, it encounters issues specifically with IE8 and IE9. <table id="table" border="1"> <tbody style="display: table-row-group"&g ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Guide for integrating the shadcn/ui Range Date Picker within a Form

Encountering an issue with using The Range Date Picker within the Form component. Specifically, I am looking to store {from, to} values of the range in an object, however, utilizing an object as a Form field value results in error messages not functioning ...

Parsing Json in AWS with Gson Library

Currently I am extracting pricing data from the http://aws.amazon.com/ec2/pricing/pricing-ebs-optimized-instances.json. Here is an example of the code to retrieve it: public class SampleJson { @SuppressWarnings("unchecked") public static void main(String ...

What do you do when schema.parseAsync cannot be found?

Currently facing an issue with zod validation in my Node.js environment, specifically encountering the error: TypeError: schema.parseAsync is not a function Despite attempting various solutions like re-importing and troubleshooting, I am unable to resol ...

The jQuery autocomplete feature seems to be malfunctioning as no suggestions are showing up when

I am currently generating input text using $.each: $.each(results, function (key, value) { if (typeof value.baseOrSchedStartList[i] != 'undefined') { html += "<td><input type='te ...

What methods can be utilized to create sound effects in presentations using CSS?

Let us begin by acknowledging that: HTML is primarily for structure CSS mainly deals with presentation JS focuses on behavior Note: The discussion of whether presentation that responds to user interaction is essentially another term for behavior is open ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...