JavaScript code to access each nested object and flatten only the top level of the object

Currently, I am working with an array of objects that has a nested structure like this:

props: {
       dog: {
         default: '',
         type: String
       },
       cat: {
         default: '',
         type: String
       },
       bird: {
         default: '',
         type: String
       }
      },
      {
       dog: {
         default: '',
         type: String
       },
       bird: {
         default: '',
         type: String
       },
       fish: {
         default: '',
         type: String
       }
     }

I want to flatten the top level of this array of objects so that all nested objects are on the same level without duplicates. The desired structure is as follows:

{
   dog: {
     default: '',
     type: String
   },
   bird: {
     default: '',
     type: String
   },
   fish: {
     default: '',
     type: String
   }
}

Since I don't know in advance what keys will be present in the structure, I need to loop through it dynamically without specifying any key names. I have attempted to extract each individual nested object and store them into an array using the following code snippet:

const newArray = [];

for (let i = 0; i < objSize; i++) {
    // checks if properties exist
    if (JSON.stringify(petObj[i].options.props) !== '{}') {
      newArray.push(petObj[i].options.props);

      const numProps = Object.keys(newArray[i]).length;

      for (let j = 0; j < numProps.length; j++) {
        console.log(petObj[i].options.props[j]);
    }
  }

However, I am encountering issues such as null or undefined errors after adding the inner for loop. Can anyone suggest a potential solution?

Answer №1

To combine objects from an array of objects, you can use the spread operator along with Object.assign.

var data = { props: [{ dog: { default: '', type: String }, cat: { default: '', type: String }, bird: { default: '', type: String } }, { dog: { default: '', type: String }, bird: { default: '', type: String }, fish: { default: '', type: String } }] },
    result = Object.assign({}, ...data.props);

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

Utilizing *ngIf within a loop to alternate the visibility of table rows with a designated class upon clicking on rows with a different class in Angular 2

I have created a table that displays data, and within this table there are 2 tr elements with the classes default and toggle-row. When I click on a tr element with the class default, it should only toggle the corresponding tr element with the class toggle- ...

Retrieve information from a controller and pass it to a Component in AngularJs

Having an issue with passing data from a controller to a component in AngularJs. The data is successfully passed to the template component, but it shows up as undefined in the controller! See below for my code snippets. The controller angular.module(&a ...

Mobile page sliding mechanism

My website contains a div that is mostly off the page, but on hover it translates onto the main page. You can check out my website. However, this method doesn't work well on mobile devices. Hovering is not effective and I often have to click multipl ...

Executing a function on a dropdown menu in AngularJS

Currently facing an intriguing scenario that is causing me some confusion. This question is specifically for those well-versed in Angular UI Grid, but all responses are welcome. The situation revolves around a UI Grid with a dropdown functionality impleme ...

Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left. I am using create-react-app with babel/webpack and react-bootstra ...

I encountered an issue when trying to launch my React application, as the CMD displayed an npm error message stating 'npm error! missing script:start'. Can someone offer assistance with this problem?

view image details Despite spending countless hours searching through past responses and attempting to resolve this issue, I have been unsuccessful. Upon entering 'npm create-react-app' in the terminal and navigating to the correct directory, I ...

Are there any current implementations of the Media Capture API in use?

After delving into the details of the draft Device APIs, I am curious if there are any existing implementations of the Media Capture API. Ericsson has showcased a few demos but hasn't made the source code available yet. There is also a reported bug o ...

What is the best way to pass data from a child component to its parent in React?

I have a dynamic table where users can select items from a dropdown menu and add them to the list. Currently, I store the item list in the component's state to render the table dynamically. I want users to be able to click on an item in the table and ...

Accessing dynamic elements in Internet Explorer 7 and 8 using jQuery

I have generated an HTML element dynamically using jQuery. Unfortunately, I am facing difficulties accessing the element utilizing jQuery selectors in IE7/IE8. For example: var id = 45; var $comment = $('#comment-'+id); // dynamically created ...

Access Vue.js data attribute in jQuery

Is there a way to extract the data-src attribute value from the following HTML code using Vue.js? <img id="some_id" :data-src = "some_path"> I attempted to assign this value to a variable using jQuery: var imgSrc = $("img:data(src)"); Unfortunat ...

Delivering resources through the Nuxt configuration file

https://i.stack.imgur.com/2OWdE.png I came across a bootstrap template online that I want to customize for my Nuxt project. I have stored all the bootstrap files in the static folder. Within the nuxt.config.js file: module.exports = { /* ** Headers ...

Trouble with Exec Command InsertHTML: Content not Going to Correct Position in Content Editable Div Tag

Need to add an image using the insertHtml execCommand within a content editable div. Take a look at the following code snippet. function createSelection(node, chars, range) { if (!range) { range = document.createRange() range.selec ...

Deleting information from several stores in React Reflux using a single action function

In the AuthActions file, there is a straightforward function called _clear that assigns this.data to undefined. This function is only invoked when a user logs out. However, upon logging back in with a different user, remnants of data from the previous ac ...

Steps to prevent specific links from being clickable in React Native's webview component

In my React Native app, I am utilizing the react-native-webview component to display blog posts. The code I have implemented is straightforward, but my goal is to restrict the webview to only show content from the blog section of the website, preventing us ...

Automatically modify browser configurations to disable document caching

Is it possible to prevent browsers from caching pages using JavaScript? I've noticed that even though PHP has a redirection implemented once the user logs in, when they press the browser's history button, it goes back to the login form. This is b ...

How can I position two divs side by side within an Appbar?

I would like the entire Container to be in a single row, with the Typography centered as it already is, and the toggle-container to float to the right <AppBar className={styles.AppBar}> <Toolbar> <Container> ...

Concealing data by index within a THREE.Points object in three.js

I've encountered an issue with a collection of points in an object (created using THREE.Points). An example of this can be seen at https://threejs.org/examples/?q=points#webgl_interactive_points. My goal is to hide a specific point when it is clicked ...

Combining all CSS files into one and consolidating all JavaScript files into a single unified file

Whenever I need to add a new CSS or JS file, I always place it in the header section like this Add CSS files <link rel="stylesheet" href="<?php echo URL; ?>public/css/header.css" /> <link rel="stylesheet" href="<?php echo URL; ?> ...

Using Typescript to dynamically set the length of a tuple or array based on the arguments passed to a function

Here is some TypeScript code to consider: function concatTuples<T>(first: [...T[]], second: [...T[]]): [...T[]] { return [...first, ...second]; } const result = concatTuples([0, 1], [2, 3]); This function concatenates tuples. The current challeng ...

Bring in LOCAL .obj for loading with Three.js OBJLoader in a React environment

Attempting to import a local .obj file using the THREE.OBJLoader().load() function is causing issues. While it successfully loads non-local URLs such as '', loading the local file takes a long time due to downloading it every time. The setup inv ...