Grouping various array components to form a single object using JavaScript

I am working with multiple array elements and I need to merge them into a single element.

Below are the array elements:

[
    {"2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]}},
    {"2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]}},
    {"3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]}},
    {"3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]}},
    {"2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]}},
    {"2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN %","children":[]}},
    {"2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART %","children":[]}}
]

Once combined, the output should appear as follows:

{
    "2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]},
    "2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]},
    "3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]},
    "3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]},
    "2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]},
    "2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN","children":[]},                     
    "2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART","children":[]}
}

Despite using the array reduce code shown below, it is not functioning correctly:

const output = input.reduce((a, obj) => {
  a[obj.mid] = obj;
  return a;
}, {});
console.log(output);

const input = [
    {"2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]}},
    {"2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]}},
    {"3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]}},
    {"3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]}},
    {"2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]}},
    {"2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN %","children":[]}},
    {"2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART %","children":[]}}
]
const output = input.reduce((a, obj) => {
  a[obj.mid] = obj;
  return a;
}, {});
console.log(output);

Answer №1

One easy way to merge objects in JavaScript is by using the Object.assign() method like so:

const data = [
    {"2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]}},
    {"2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]}},
    {"3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]}},
    {"3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]}},
    {"2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]}},
    {"2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN %","children":[]}},
    {"2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART %","children":[]}}
];

const result = Object.assign({}, ...data);

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

Answer №2

Retrieve the initial item from the Object.entries of each object that is being looped through:

const primaryData = [
    {"2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]}},
    {"2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]}},
    {"3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]}},
    {"3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]}},
    {"2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]}},
    {"2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN %","children":[]}},
    {"2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART %","children":[]}}
]
const result = primaryData.reduce((accumulator, object) => {
  const [propertyKey, propertyValue] = Object.entries(object)[0];
  accumulator[propertyKey] = propertyValue;
  return accumulator;
}, {});
console.log(result);

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

Guide to utilizing a variable inside a string within an array in PHP

Here is a function that I need to repeat multiple times while changing the array values: register_field_group(array ( 'id' => 'acf_page-options-cat-work', 'title' => 'Featured Posts', 'fields& ...

"Using the every() method in underscore.js with an undefined parameter

I recently wrote some code and encountered an unexpected result: var a = new Array(10); // should be [undefined * 10] var b = _.every(a, function(m){ if(_.isUndefined(m)){ return false; } return true; }); I anticipated that b would b ...

Ways to implement a worldwide change in a subordinate entity

I am facing a challenge where I need to apply a global position, obtained from a WebVR controller, to a child object that is nested within multiple parent objects with transformations. The child object I want to update does not have any transformations app ...

Performing matrix addition with pointers

If I pass (c,a,b) to the function add_mat, where the result of a,b is stored in c as shown below: void add_mat(int c[][3], int a[][3], int b[][3], int m, int n) What return type should add_mat have if constructed in this way? ?? add_mat(int a[][3], int ...

Using AngularJS and Web API to generate a dropdown menu from a one-to-many relationship

I have two tables in my database: People and Payband. Let me simplify the relationship below: dbo.People PersonId : int (Primary Key) FirstName : string MiddleInitial: string LastName : string DateOfBirth: datetime PaybandId : int (Foreign Key) dbo.Payb ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

Iterate through every multi-dimensional array and output a single array

This is a multidimensional array: Array ( [CalculateOverheadDoorSpringsResult] => Array ( [SpringForce] => Array ( [InputData] => Array ( ...

Vue-router and middleman combination displaying '404 Error' upon page refresh

I'm in the process of developing a website that utilizes Middleman (Ruby) on the backend and VueJS on the front end, with vue-router managing routing. Specifically, in my vue-router configuration, I am rendering the Video component on /chapter/:id as ...

Using an if-else statement within a Vue event listener

Can this task be achieved using Vue: <button @click="(true) ? funcA : FuncB"> Click </button> In this scenario, the event is a click, however it could also involve keypress, keydown, input or any other events documented in vuejs. If ...

Creating a vibrant 2D triangle with unique coloring using the power of three.js

Struggling with setting up a basic 2D scene using Three.js. The goal is to display a red triangle in a 2D view, but I am facing difficulties achieving that. I suspect the following components are essential: THREE.OrthographicCamera A simple triangular sh ...

Strategies for managing large arrays in JavaScript

I'm currently working on finding the most effective approach for handling large datasets in JavaScript. Specifically, I am dealing with files containing data spanning four hours read at a 100ms interval. When all the data is loaded into a one-dimensi ...

Issue with Angular's ng-show failing to display an image post-processing

$scope.showProcessedGraph = function(hash) { if ($scope.selectedFile.hash == hash) return; $scope.graph = ""; $scope.isImageLoaded = false; $scope.isLoading = true; if (hash) { $http({ m ...

I'm running into difficulties when it comes to processing a JSON document

I've come across a .json file online that I'm trying to work with, but it seems like there may be an issue with the file itself. Since I'm not very familiar with .json files, my plan is to convert it into a CSV format. Unfortunately, I haven ...

The customTypeMapping for 'JSON' is currently experiencing issues with Apollo GraphQL on Android

My build.gradle file contains customTypeMapping['JSON'] = "kotlin.Any" Inside my graphql file, there is a mutation named UpdatePropertyInfo with variables: $id: ID $extra_beds: [JSON] { update_property_info( id: $id ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Working with JSON data in PHP and JavaScript

I'm attempting to send a JavaScript object to a PHP script using jquery.ajax(), like so: var bigArray = new Object(); //Code //Start loop bigArray[x] = {name: exname, id: exID, order:e, set: setBox, inc: incBox, example: exampleBox, day: i}; It&apos ...

Combining multi-dimensional array elements with varying delimiters in PHP

I need to transform a multi-dimensional array into a string (implode) in such a way that I can convert it back to the original array later (explode). Is there a method to implode while retaining the keys? Let's take a look at an example of my array s ...

The data from Ajax response is not showing up on the datatable when accessed through Firefox and Edge browsers

I am facing an issue where my report displays correctly on Google Chrome, but when I try to view it on Firefox or Edge browser, the JSON response is shown on the browser instead of the data table. A sample response is shown below: " [{\"RegisteredBy ...

What is the best way to skip rows that throw errors in Redshift/Postgres? (Dealing with invalid JSON in json_extract_path_text)

Struggling with running a query in Redshift where I'm utilizing json_extract_path_text. Unfortunately, some JSON entries within the database column are invalid. The Issue: Whenever the query encounters an invalid JSON value, it halts and throws a "JS ...

Populate an Angular 2 variable with JSON data fetched from an HTTP Request

I am relatively new to Angular2 and I am currently working on extracting key/value pairs from a JSON file that is returned by an HTTP request. My goal is to save this data in the objectResource property so that I can later access it in the template. This ...