I want to combine the objects in each array using JavaScript, but I'm unsure how to reduce the array without knowing the key value names

I have an array within another array and I would like to condense the subarrays into one object each. Below is the code snippet that generates the initial array:

const final = data.formEntryData.map((item) => {
    let key = Object.values(item.data);
    let test = data.hmm.map((array) => {
      return { [array.name]: key[array.arrayOrder] };
    });
    return test;
  });

Here is the original array structure:

[
  // Subarrays here
]

I aim to merge the subarrays so they resemble this format:

[
  // Merged objects here
]

I have tried using the reduce method as shown below:

var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];
var object = final.reduce(
  (obj, item,) => Object.assign(obj, { [item.key]: item.value }), {});

console.log(object)

However, I am struggling because the names for item.key and item.value are dynamically derived in the map function. Any assistance on this issue would be highly appreciated. Thank you!

Answer №1

Using this special function with the array you provided, you can effectively combine the nested arrays into objects. This function utilizes Object.entries to access the properties of each object.

function mergeArrays(arr) {
  return arr.map(innerArray =>
    innerArray.reduce((mergedObj, obj) => {
      Object.entries(obj).forEach(([key, value]) => {
        mergedObj[key] = value;
      });
      return mergedObj;
    }, {})
  );
}

The result is as follows:

[
  {
    'Product Name': 'Coffee Beans',
    'Product Description': 'Freshly roasted coffee beans',
    'Product Image': 'coffee-beans.jpg',
    'Price': '$10.99',
    'Availability': 'In stock'
  },
  {
    'Product Name': 'Green Tea',
    'Product Description': 'Organic green tea leaves',
    'Product Image': 'green-tea.jpg',
    'Price': '$5.99',
    'Availability': 'Out of stock'
  },
  ...
}

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

In three.js, it appears that shadows are not being cast by imported 3D objects

Hey there, I've been diving into three.js recently and managed to successfully import a 3D model from Cinema 4D using the three.OBJMTLLoader. However, I'm having trouble getting the imported object to cast a shadow. I've tried setting object ...

VueJS Tutorial: Revealing the Nearest Hidden Element in a List of Items

Is there a way to toggle the visibility of the nearest div element by clicking a button in vue? Lets imagine I have a collection of items, each containing hidden information. <ul> <li v-for="item in items" :key="item.id"> <div> ...

Traverse JSON data using associative loops

Is there a way for me to iterate through this JSON data without using numerical indexes? I want to treat it like an associative array. This is what I have so far: $.post('/controlpanel/search', { type: type, string: string }, function(data){ ...

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

Having trouble customizing the HTML range input?

I am looking to customize the appearance of a range input slider. Specifically, I want the slider to be green for the lower portion (where the thumb has moved) and grey for the remaining section. I have successfully changed the default styles from blue and ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

A guide to downloading files through your web browser

Currently, I am working on a project to download videos from the browser using youtube-dl for educational purposes. I have encountered an issue regarding downloading local mp4 files in the browser using axios. The download starts successfully; however, af ...

What is the method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function. Example of current malfunctioning code: const _validations = { userID: (req) => check('userID').isString().isUUID(&apo ...

Why do I keep receiving values only from the initial form? What could be the issue?

I am facing an issue on my website with multiple forms. The problem arises when the "Save" button is clicked, as it continues to check the fields in the first form instead of the form where the button is located. Here is a snippet of my current Ajax scrip ...

Traversing an array of objects using D3.js

I'm attempting to create a row of bars that are all the same height and width based on their titles. I have an array of 100 objects, each with a key called results containing another array of 20 objects. This means I should end up with a row of 2000 b ...

Is Formik Compatible with TextareaAutosize?

I've implemented react-textarea-autosize and formik in my project, but I'm having trouble connecting the change events of formik to TextareaAutosize. Can anyone guide me on how to do this properly? <Formik initialValues={{ ...

Create a new variable and compile the sass/less file when it is requested

I'm exploring options to utilize Node.js or another server-side language to handle a specific type of request. For instance, receiving a request like this: The goal is to extract the value from the URL parameter and use it to dynamically update a var ...

Adding a div dynamically in AngularJS based on a certain condition

I am facing a challenge with appending the next message content to an existing div in my messages array. I want to avoid creating a new div if the next message id is the same as the previous one. Although my code logic attempts this, it's not quite t ...

Why am I unable to make a selection in the dropdown menu?

Can anyone help me figure out why I am unable to select an option from the material ui library and display it in the state? Has anyone else encountered this issue? For a detailed code example, check here import React from "react"; import ReactDOM from " ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

The ins and outs of implementing i18n on an Angular component library

My custom component library is not functioning properly with i18n within my module // To enable Ahead-of-Time compilation, a function must be exported for factories export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(ht ...

Stop the interval when the variable equals "x"

I've created a function that controls a specific row in my database using AJAX. The function is triggered by a click event and placed within a setInterval function to check ten times per second. Initially, it will return 0, but eventually (usually wi ...

Is there a way for me to determine the total number of seconds since the chatbot was first opened?

Here is a snippet of my HTML code: <div class="chatbot chatbot--closed "> <div class="chatbot__header"> <p><strong>Got a question?</strong> <span class="u-text-highlight">Ask Harry</span></p> <s ...

Click on the appended text to remove it using Jquery

Seeking a more efficient and streamlined approach for appending and removing appended spans, divs, or text. Below is the code snippet - any insights on what could be improved? /* HTML CODE */ <div id="appendHere" style="padding:10px;border:solid 1px ...

Is there a workaround for unresolved symlink requirements when using npm link?

Creating an NPM package often involves using the following: npm link This allows for making modifications to a package called <myPackage> during development without constantly having to publish and unpublish! Developers can make changes locally and ...