What is the best way to bring a nested object to the top level without deleting the original top level

Imagine having the following dataset:

data = [{
    "_id" : "2fApaxgiPx38kpDLA",
    "profile" : {
        "name" : "Karina 1",
        "avatar" : "avatar1.jpg",
        "bio" : "my bio 1"
},
{
    "_id" : "NXM6H4EWfeRAAhB7c",
    "profile" : {
        "name" : "Karina 2",
        "avatar" : "avatar2.jpg",
        "bio" : "my bio 2"
    },
}];

I used _.map(data, "profile") but it removed the top-level _id:

wrongResult = [{
    "name" : "Karina 1",
    "avatar" : "avatar1.jpg",
    "bio" : "my bio 1"
},
{
    "name" : "Karina 2",
    "avatar" : "avatar2.jpg",
    "bio" : "my bio 2"  
}];

How can I move the nested objects to the top level without removing the top level like this:

expectedResult = [{
    "_id" : "2fApaxgiPx38kpDLA",
    "name" : "Karina 1",
    "avatar" : "avatar1.jpg",
    "bio" : "my bio 1"
},
{
    "_id" : "NXM6H4EWfeRAAhB7c",
    "name" : "Karina 2",
    "avatar" : "avatar2.jpg",
    "bio" : "my bio 2"  
}];

Your help is greatly appreciated. Thank you!

Answer №1

Is this somewhat similar? (unverified)

_.map(data,function(d){
    d.profile._id = d._id;
    return d.profile;
});

Answer №2

Recently, I encountered a similar task and crafted a versatile function to flatten all object values (including nested ones) to the top level:

const flattenObjectValues = (obj, cache = {}) => {
    const objectValues = Object.keys(obj).reduce((acc, cur) => {
        if (!Array.isArray(obj[cur]) && typeof obj[cur] === 'object') {
            return flattenObjectValues({ ...acc, ...obj[cur] }, cache);
        }
        acc[cur] = obj[cur];

        return acc;
    }, {});

    return {
        ...objectValues,
        ...cache,
    };
}
flattenObjectValues({
  a: {
    b: 'a',
    c: 'b',
  },
  d: {
    e: 'a',
    f: {
      g: {
        h: [
          1,
          2,
          3,
        ]
      }
    }
  }
});
=> { b: 'a', c: 'b', e: 'a', h: [ 1, 2, 3 ] }

An drawback of this function is that it may overwrite keys with the same name.

Answer №3

Utilize the flatten function to bring the nested object up to the parent level...

Answer №4

If you're utilizing lodash, I've devised a versatile function to flatten any deeply nested object.

const flattener = obj => {
        const toPairs = obj => _.entries(obj).map(([key, val]) => typeof val === 'object' ? toPairs(val) : [key, val]);
        return _.chain(toPairs(obj)).flattenDeep().chunk(2).fromPairs().value();
    }

For instance, consider an array like this:

data = [
{
    "_id" : "2fApaxgiPx38kpDLA",
    "profile" : {
        "name" : "Karina 1",
        "avatar" : "avatar1.jpg",
        "bio" : "my bio 1"
    }
},
{
    "_id" : "NXM6H4EWfeRAAhB7c",
    "profile" : {
        "name" : "Karina 2",
        "avatar" : "avatar2.jpg",
        "bio" : "my bio 2"
    },
}
]

You can then execute:

data.map(obj => flattener(obj))

This will yield:

[
    {
        "_id": "2fApaxgiPx38kpDLA",
        "name": "Karina 1",
        "avatar": "avatar1.jpg",
        "bio": "my bio 1"
    },
    {
        "_id": "NXM6H4EWfeRAAhB7c",
        "name": "Karina 2",
        "avatar": "avatar2.jpg",
        "bio": "my bio 2"
    }
]

Note: The flattener function eliminates duplicate object keys. So, for an object like;

myObj = { name: 'rick', age: 10, country: { name: 'uganda' } }

Calling flattener(myObj) would result in:

{ name: 'uganda', age: 10 }

instead of:

{ name: 'uganda', age: 10, name: 'rick' }

as an object cannot have two identical keys even with unique values assigned to them.

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

Steps for handling errors in Node.js when the query result rowCount is 0 and throwing an error in response

If the rowcount is 0, I need to send a response as failed. If the rowcount is 1, I need to send a success status. Can someone please assist me with this? When I try to print (client.query), it displays the result in JSON format (refer to attached image). ...

How can we display data from the database in a table if the data is stored as a string separated by commas using Ajax?

I am having trouble displaying 33 and 123 of heading 1 and heading 2 in a new row. Can someone please help me with this issue? Even though I updated the code, the for loop is only showing the last value. $.ajax({ type:"POST", url:"{{route(&ap ...

What is the best way to implement OTP expiration time in Next.js using Firebase?

Could anyone please help me with setting the OTP expire time in Next.js using Firebase? I have searched through the Firebase documentation but haven't been able to find a solution to my issue. Below is the code I am using to send the OTP: const appV ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in. However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even ...

Using JavaScript to enhance event handling for a `select` element in a progressive manner

I have an advanced <select> element in my HTML. It is structured like this: <ul> <li></li> <li></li> ... </ul> In the current setup, a click event handler is attached to each individual li element. If the ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

"Cross-origin resource sharing problem while working with NodeJs, Express, and React on

Currently, I am working on a small project where I am using NodeJs and Express for the backend and React for the client side. In order to tackle CORS policy issues, I have implemented the "cors" npm package on the server side, but unfortunately, it doesn& ...

Tips for preventing timeouts when posting data to Heroku servers

I have a Ruby on Rails application deployed on Heroku. The app includes 8 optional text fields that users can choose to fill or leave empty as needed. However, the more text fields a user fills out, the heavier the processing load on my app. If there are ...

Create unique identifiers for the TD elements of Viz.js that will be displayed within the SVG elements

Below is the DOT code snippet in Viz.js that I am working with: digraph G { node [fontname = "font-awesome"]; 17 [id=17, shape="hexagon", label=<<TABLE BORDER="0"> <TR><TD>undefined</TD></TR> <TR><TD>[47-56]< ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Customize the appearance of the Vue.js datepicker starting from today's date

I am currently using the vue-datepicker component to display a date input field in my form. I want to set the default date to the current day and disable the selection of past dates. Additionally, I need to change the language of the component but it seems ...

The error was thrown at line 800 in the loader.js file of the internal modules

When I ran yarn install in my project folder, I encountered the following error: internal/modules/cjs/loader.js:800 throw err; ^ Error: Cannot find module 'ts-node/register' Require stack: - internal/preload ?[90m at Function.Module._resolveF ...

Tips for creating animations using parent and child components in Angular

Despite my best efforts, it seems like this should be functioning properly... but unfortunately it's not... I'm attempting to achieve a transition effect on the parent element (ui-switch-groove) while the child element (ui-switch-dongle) moves. ...

Unreliable Raycasting with Three.js

I am attempting to identify clicks on my Plane mesh. I have established a raycaster using provided examples as instructions. Below is the code snippet: http://jsfiddle.net/BAR24/o24eexo4/2/ Clicks made below the marker line do not register, even if they ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

Ensure that the loader remains visible until all data has been successfully retrieved from the AngularJS service

Currently, I am facing an issue with the implementation of angularjs ui-router for state transitions along with a loader assigned to each view. The problem arises when moving from one state to another and the loader disappears before all the content from t ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

Can anyone help me figure out the best way to test for observable errors in Angular2?

I'm currently working on creating unit test cases for my Angular2 components. Up until now, the test cases have been running smoothly. However, I've run into some issues with my asynchronous calls. For example, I have a method for creating a n ...