Collapse an array containing objects with nested objects inside

Similar questions can be found here and here, but I am struggling to modify the code provided in the answers to fit my specific needs due to its conciseness.

The structure of my array of objects is as follows:

[
    {
        id: 1,
        someProp: "value of some prop",
        metaData: {
            metaId: 123
            uuid: "2348_4354_dfgg_r343"
        }
    },
    {
        id: 2,
        someProp: "value of some prop again",
        metaData: {
            metaId: 321
            uuid: "9897_3543_ergl_j435"
        }
    }
]

I need to transform it into the following structure:

[
    {
        id: 1,
        someProp: "value of some prop",
        metaId: 123
        uuid: "2348_4354_dfgg_r343"
    },
    {
        id: 2,
        someProp: "value of some prop again",
        metaId: 321
        uuid: "9897_3543_ergl_j435"
    }
]

The goal is to merge the properties from the nested metaData object into the parent object for each item in the array. I have attempted the following code:

console.log(Object.assign(
    {}, 
    ...function _flatten(o) { 
        return [].concat(...Object.keys(o)
            .map(k => 
                typeof o[k] === 'object' ?
                    _flatten(o[k]) : 
                    ({[k]: o[k]})
            )
        );
    }(events)
));

However, this code only creates one flattened object, whereas I need to flatten multiple objects in the array.

Answer №1

One way to handle the nested object is by spreading it out.

const
    data = [{ id: 1, someProp: "value of some prop", metaData: { metaId: 123, uuid: "2348_4354_dfgg_r343" } }, { id: 2, someProp: "value of some prop again", metaData: { metaId: 321, uuid: "9897_3543_ergl_j435" } }],
    result = data.map(({ metaData, ...o }) => ({ ...o, ...metaData }));        

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

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

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

Executing a closure within a promise's callback

Currently, I am working on implementing a queue system for a web application in order to locally store failed HTTP requests for later re-execution. After reading Mozilla's documentation on closures in loops, I decided to create inner closures. When ...

Angular library is being excluded from the R.js optimizer process

I'm encountering difficulties when trying to optimize an Angular project with the r.js optimizer. Everything works smoothly when I use grunt-requirejs for optimization, but as soon as I attempt to exclude Angular from the build, I encounter an error ...

Is there a way to align the Material UI mobile menu to the left edge of the screen?

Need help with this UI issue: Currently working on designing a mobile web app using React and Material UI. I'm struggling to get the sidebar menu to start from the left edge of the screen, as it seems to have an unwanted margin preventing it. Any sug ...

The function parseFloat in Javascript can be used to subtract two numbers, returning an integer value

Apologies for the inconvenience, but I could really use some assistance. I attempted to convert a string into a decimal and was successful, although I encountered an issue: number = document.getElementById("totalcost").innerHTML; //String that rep ...

Having trouble loading a JSON object into a Datatable using Jquery?

I am currently utilizing DataTables in combination with Jquery. I have a data source in the form of an JSON object that I intend to retrieve via Ajax and showcase within the table. The JSON data is retrieved from the /live/log url and has the following fo ...

What is the best way to create a unique custom control in Javascript, potentially utilizing jQuery?

My goal is to develop a custom control using JavaScript that includes methods, properties, and events, and can be rendered within a div element. For example, one such control could be a calendar. It would display in a div, with customizable properties for ...

Transforming the elements within an array of objects into individual key-value pairs and then adding them to a fresh array

Hello, I am diving into the world of Typescript/Javascript and encountering some challenges when it comes to manipulating arrays of data. Please bear with me as I navigate through my learning curve. Imagine having an array of objects structured like this: ...

Combining two elements in a React application

Having a collection of assets and their quantities: const bag = { eth: 50, btc: 30, kla: 10, set: 5, ova: 5 }; const assetList = { eth: { name: "Ethereum", icon: "urlhere", colour: "#030", text: "light&q ...

A guide on iterating through added inputs within an array

I am working on submitting multiple appended inputs through an API. The issue I'm facing is that the number of items varies each time. Upon form submission, only the last appended input is successfully submitted, and I receive an object in return. How ...

Choosing the second option is not possible after selecting from the initial drop-down menu

After some investigation, I managed to find a way to display a specific productCategory based on the selection from the first dropdown menu. https://i.sstatic.net/AsLE2.png However, when attempting to choose a productCategory, nothing seems to change. T ...

What could be the reason that the _.sample function in lodash is producing a return type of number

Sample Scenario 1 const myNumber = _.sample([1, 2, 3]); // Anticipated data type: number // Real data type: number Sample Scenario 2 const arr = [1, 2, 3] const myNumber = _.sample(arr); // Anticipated data type: number // Real data type: number | undefin ...

Tips for performing matrix manipulation in Matlab:

I have two matrices in Matlab: matrix A of size m x n and matrix b of size 1 x n. Matrix b is structured such that it contains sequences of increasing values up to a certain number k (e.g. b = [1 1 1 2 2 3], n = 6). My goal is to iterate through each row ...

Issues have arisen with the @keydown.ctrl and @keyup.ctrl event modifiers in Vue.js, as they are not properly responding

I have a project in VueJS where I need to implement a custom context menu that will pop up when the user hovers over specific elements on the page. This context menu is dynamic, meaning it changes as the user moves between different items. If the user hold ...

Typescript's date function offers a variety of useful features

Can anyone help me create a function that formats a date string for sorting in a table? The date is in the format: 08.04.2022 16.54 I need to convert this to a number or date format that can be sorted. I'm new to TypeScript and could use some guida ...

From organizing nested arrays in jSon to visualizing data with D3js

I am completely new to working with d3 and JSON. I have a piece of data from JSON that I am attempting to extract, and I'm wondering if I am headed in the right direction. My goal is to display a rectangle graph for each server within different statu ...

Transforming the current date() into a distinctive format, encompassing the utilization of T

Background In my Angular UI, I have a datepicker that is defined as: <date-picker name="contractEndDate" date="employee.contractEndDate"></date-picker> When the button is clicked, the contractEndDate value changes from null to the current da ...

RectAreaLight in Three js does not produce any light reflection when used with MeshPhongMaterial due to lack of support for OES_texture_half

After trying to incorporate a RectAreaLight into my three.js scene where I have objects with MeshPhongMaterial, I noticed that there is no light reflection on the objects. A useful example can be found here: Link If you open the developer tools, you can s ...

Tips for incorporating additional items into an established useState array utilizing map() or foreach()?

I'm working on developing a social media platform similar to Twitter, and I'm facing challenges with the news feed functionality. Essentially, the news feed is supposed to fetch tweets from my firebase database for each user followed by the curre ...

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...