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

Error message indicating that the preflight request failed access control check in Angular 5 with JWT OAuth integration

After spending hours reading through several posts, I have yet to find a solution to a very common problem. It seems that in order for my JavaScript code to access the resource, the server must include the Access-Control-Allow-Origin header in the response ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

I am having trouble executing a script as the steps I have followed are not yielding the desired results. I am wondering where I may have made a mistake

I am trying to execute a script provided by Maciej Caputa in response to this question: How to import CSV or JSON to firebase cloud firestore The objective is to utilize a JSON file for uploading data to Cloud Firestore. As a newcomer to running scripts, ...

retrieve data for chart from an AJAX request

I am looking to create a chart using amCharts and I have received some values from the server through an ajax call. Now, I need help in utilizing this data for my chart. Can anyone guide me on how to achieve this? var chart = am4core.create("chartdiv& ...

What is the reason behind AngularJS throwing an error related to bad augmentation?

Whenever I try to update the src link in my Angular code from version 1.2.2 to 1.5.0, I encounter an error. The code works perfectly fine with 1.2.2, but switching to 1.5.0 throws an error. I want to upgrade it to 1.5.0, so what changes do I need to make ...

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...

What could be causing my React Router to fail in displaying the content of Home.js?

My <Route> is not functioning as expected The Route leading to the homepage does not show the content from the Home.js file import "./App.css"; import Navbar from "./components/Navbar"; import { BrowserRouter as Router, Route, Ro ...

Utilizing erb within a coffeescript file for modifying the background styling

Is there a way to change the background image of a div based on user selection from a dropdown menu? For instance, if the user picks "white" the background image becomes white, and for "red" it changes to red. I'm struggling with this in coffeescript ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

Unexpected behavior observed with Async/Await

I am currently learning how to use Async/Await, which is supposed to wait until the Await function finishes executing before moving on with the code. However, I have encountered an issue where my code stops completely after using Await. Here is the method ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

Protractor can now successfully locate and interact with a nested button element

I am trying to click on the second button, but I can't differentiate between the two buttons using class names. div class="ng-view ff-domain ng-scope"> <div class="hero-unit blur-background ng-scope"> <h1></h1> <h2> ...

Is there a CSS3 Selector With Similar Functionality to jQuery's .click()?

For a few years now, I have been utilizing a pure CSS navigation system. However, with the recent increase in mobile site projects at my workplace, I am encountering issues with drop-down menus not functioning properly on mobile devices. Despite this chall ...

What situations warrant the use of unescaped !{} in pug for string interpolation?

Is there a practical application for utilizing !{} - string interpolation in an unescaped format, despite the potential risks associated with its use? I have reviewed the information provided at these sources: Using !{ } and #{ } interpolation in a jade ...

Leveraging the useContext and useReducer hooks within NextJS, while encountering the scenario of reading null

Trying to develop a tic-tac-toe game in NextJS and setting up a board context for my components to access. However, after integrating a reducer into the Wrapper to handle a more complex state, I'm encountering a null error. Errors: TypeError: Cannot r ...

What is the most stylish method for merging a removeCartItem function with an addCartItem function?

Is there a way to combine these functions into a more concise and elegant piece of code? While the current setup works fine, it feels redundant to have two large functions that essentially do the same thing. const modifyCartItem = (cartItems, productToMo ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Determine the number of properties present in two arrays by comparing them

Looking to compare two arrays and determine the count of items in the master list. A sample master list could be: { name: 'Emily', age: 29 }, { name: 'Jack', age: 31 }, { name: 'Lily', age: 28 }, { name: 'Emily', a ...

Tips on stopping the page from scrolling following an ajax request (return false not effective or potentially misplaced)

I am working on a project that involves displaying a tree with information from the Catalogue of Life, including details such as Kingdom, phylum, order, and more. My approach includes using ajax/php to interact with a mySQL database and javascript to handl ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...