Combine the entities within the object

I need to combine two objects that contain other objects within them, similar to the following structure:

let selections = {
    123: {
        abc: {name: 'abc'},
        def: {name: 'def'}
    },
    456: {
        ghi: {name: 'ghi'},
        jkl: {name: 'jkl'}
    }
};

let flatSelections = Object.keys(selections).reduce((r, k) => {
    return selections[k];
}, {});

console.log(flatSelections);

/* expected data
flatSelections = {
    abc: {name: 'abc'},
    def: {name: 'def'},
    ghi: {name: 'ghi'},
    jkl: {name: 'jkl'}
};
*/

However, when I execute the code snippet, I only get the output of selection['456']. https://jsfiddle.net/benlesc/uw65bjo1/13/

Answer №1

Make sure to return the modified accumulator from the reduce function by using either Object.assign or Spread syntax to combine accumulator (r) with item (k).

Additionally, utilize Object.values since you only need to consider values.

let selections = {
    123: {
        abc: {name: 'abc'},
        def: {name: 'def'}
    },
    456: {
        ghi: {name: 'ghi'},
        jkl: {name: 'jkl'}
    }
};

let flatSelections = Object.values(selections).reduce((r, k) => {
    return Object.assign(r, k)
}, {});

console.log(flatSelections);

Answer №2

To simplify the process, you can utilize the reduce method with Object.values().

let data = {
    123: {
        apple: {type: 'fruit'},
        banana: {type: 'fruit'}
    },
    456: {
        orange: {type: 'citrus'},
        grape: {type: 'berry'}
    }
};

const result = Object.values(data).reduce((acc, curr) => {
    return {...acc, ...curr};
}, {});

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

Answer №3

Try utilizing the Object.assign() method

let choices = {
    123: {
        apple: {type: 'fruit'},
        banana: {type: 'fruit'}
    },
    456: {
        carrot: {type: 'vegetable'},
        broccoli: {type: 'vegetable'}
    }
};

let result = Object.assign(choices["123"] , choices["456"])
console.log(result)

You can expect to receive an output of

{"apple": {"type": "fruit"}, "banana": {"type": "fruit"}, "carrot": {"type": "vegetable"}, "broccoli": {"type": "vegetable"}}

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

Leveraging the reduce method in processing JSON data

Here is the JSON data I have: { "meta": { "totalPages": 13 }, "data": [{ "type": "articles", "id": "3", "attributes": { "title": "AAAAA", "body": "BBBB", "created": "2011-06-2 ...

Remove search results in real-time

I'm currently working on implementing a search feature for a web application. While I have made some progress, I am facing an issue with removing items when the user backspaces so that the displayed items match the current search query or if the searc ...

I am attempting to create a skybox, yet it seems like I am overlooking a crucial element

Currently, I am attempting to create a skybox but have encountered difficulties with various tutorials. Initially, I tried to use an array approach to pass parameters for the material based on a previous example, but it seems that the method has been updat ...

Combine bar and stacked bar charts on a single graph with morris.js

Can a combination of a stacked bar chart and a regular bar chart be created in morris.js? I have successfully generated a stacked bar chart using the following code: Morris.Bar({ element: 'bar-example', data: [ {x: '2011 Q1', ...

What steps can be taken to resolve the issue with Angular routing?

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {HomeComponent} from "./home/home.component"; import {SettingsComponent} from "./settings/settings.component"; ...

What steps do I need to take in Bootstrap 5 to add a search icon to the navbar that reveals a search box beneath it when clicked?

I've made progress on the navbar design Now, I'm looking to add a search icon next to the login button. Clicking on the search icon should reveal a search box below the navbar, similar to the image shown below. My transparent navbar has a relati ...

Unable to choose radio button again

Check out this fun web quiz I created! I'm having some trouble with the back button functionality. Whenever a user clicks back, I want to restore their previous choice but for some reason it's not working as expected. Take a look at my go_back ...

Develop a personalized API using Strapi that involves integrating data from two distinct tables

I am relatively new to Strapi, so please forgive my lack of experience. My goal is to set up a custom route for retrieving complex data using two related tables. I have relationships with the "items" and "comments" tables. My approach involves selecting ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Steps for removing all inline styles within an element:1. Access the element's

I have a group of span elements containing texts generated by tinymce. <span class="ArticleSummary"> This content is produced using a text editor and may include various inline styles. </span> Typically, this text includes numerous inline s ...

Executing asynchronous promises within an asynchronous promise using the .join() method

I am currently utilizing node/express, MySQL, and Bluebird for my project. When handling client requests, I am performing async database operations. After the initial database operation callback, I need to carry out some calculations before executing two ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

What is the process for configuring socket.io to solely listen on a single designated route?

Is there a way to make socket.io listen only on my /home route, instead of every route? I tried changing the configuration but it only displayed a JSON file on the home path. const server = require('http').Server(app); const io = require('s ...

Increased impact of dynamically added elements following page transition

After implementing dynamic functionality from jQuery in my code, I encountered an issue where if I navigate back one page and then return to the original page containing the added elements, they seem to trigger twice upon clicking. To troubleshoot, I incl ...

Is it possible to dynamically assign trigger and target divs to bPopup?

On our ColdFusion page, we have a dynamic list of paired divs created using a loop over a query. For example, each pair consists of internshipHandleX and internshipHiddenX: <div id="internshipHidden#internship.currentrow#" class="hidden pop-up"> We ...

Error message: When working with Protobuf, an uncaught reference error occurs because the 'exports

Currently, I am in the process of configuring protobuf to work with typescript. According to the official Google Documentation, all that is needed is to execute npm install google-protobuf and then to include require('google-protobuf'). Unfortu ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Ant design of the card

I am struggling to make the image appear in full width within the ant design card component. import React, { useState, useEffect } from 'react'; import uno from '../images/dualComida.jpg' import { Button, Space, Typography, ...

Incorporating an image as a clickable element instead of a traditional button using HTML and

Here's the issue at hand: I currently have "+" and "-" icons at the end of each row to add and delete rows as needed. However, I would like to replace the "-" icon with a trashcan symbol instead. I attempted to do this by replacing it with an image s ...