Generating a collection of objects using arrays of deeply nested objects

I am currently working on generating an array of objects from another array of objects that have nested arrays. The goal is to substitute the nested arrays with the key name followed by a dot. For instance:

const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
result = ["id", "name", "obj.lower", "obj.higher"]

I have been successful in extracting the nested keys and values, but I am facing difficulties in getting the objects from the array.
For example (expected result):

const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
const newData = [{id: 5}, {name: "Something"}, {obj.lower: True}, {obj.higher: False}]

I have tried the following approach:

 getValues = object => Object.entries(object).flatMap(([k, v]) => {
    if (typeof v !== "object") {
      return {[k]: v}
    }
    return v && typeof v === 'object' ? this.getKeys(v).map(s => `${k}.${s}`) : [k];
  });

Next, I will be comparing these filtered array of objects with user data that looks like this:

export const requiredKeys = {
  data: {
    id: null,
    status: null,
    summary: null,
    // "updated_by.id": null,
    // "updated_by.firstname": null,
    // "updated_by.lastname": null,
    // "updated_by.username": null,
    // "updated_by.blocked": null,
    // "pillars.pillarsType": null,
    // "student.created_by": null,
    // state: null,

Answer №1

You have the option to extract key/value pairs or nested object pairs in order to generate new objects from these entries.

const
    getProperties = obj => Object
        .entries(obj)
        .flatMap(([key, value]) => value && typeof value === 'object'
            ? getProperties(value).map(([subKey, subValue]) => [`${key}.${subKey}`, subValue])
            : [[key, value]]
        ),
    data = { id: 1, item: "Item 001", obj: { name: 'Nilton001', message: "Free001", obj2: { test: "test001" } } },
    result = getProperties(data).map(pair => Object.fromEntries([pair]));

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

How can I use Node.js Express to upload files with Multer?

I am facing an issue while trying to upload a file image using multer in express. The file gets successfully uploaded to the directory, but the name of the file is not being saved in the database. I am utilizing mongodb with express and currently, the file ...

Challenges when building a production version of an Expo app with Typescript

Attempting to perform a local production build, I ran expo start --no-dev --minify. Only the initial template file displays, stating "Open up App.tsx to start working on your app," and none of my work is visible... Has anyone else encountered this issue a ...

Step-by-step guide on incorporating edit, update, and discard functionalities within an Angular Material table component (mat-table)

I am currently working on implementing edit, update, and discard functions in an angular material table. While I have been able to successfully edit and update the table row wise, I am struggling with how to discard table rows. If you would like to see wh ...

Changing a List within a Structure

I have been working on a project for my coding class, specifically focusing on C#. I have a seemingly simple question that has left me puzzled as I cannot seem to find an answer anywhere. While searching, all I keep finding are results on how to create a l ...

Why does AngularJS treat $http response.data as an object, even though PHP sends back a JSON string?

I am struggling with an AJAX call to PHP. The Angular code seems simple: $http( { // ... } ) .then( function cf_handle_success( response ) { console.log( response.data ) ; // --> [object Object] } , ...

A Study on Particle Systems using THREE.js

While working on my particle System in THREE.js with SPARK.js, I have completed the necessary code for the system. However, I am facing an issue where nothing related to the Particle System is being displayed on the screen. Currently, I am trying to creat ...

Unleashing the Power of Firebase Service in Angular Components: A Guide to Effective Unit Testing

I am currently working on testing my Create-User-Component which relies on an Auth Service that includes methods like 'login, logout,' etc. The Auth Service imports both AngularFireAuth and AngularFirestore, and it is responsible for handling da ...

Reorganizing array of objects in JavaScript

Currently, I am tackling a challenge within a ReactJS application. My task involves extracting JSON data related to various products and restructuring this information for the purpose of categorization and displaying it accordingly. Despite my attempts wi ...

Utilizing DOMStringMap data to populate CSS URLs

I am attempting to create a universal CSS modification for a webpage element that resembles: <button data-action="link" class="cardImageContainer coveredImage cardContent itemAction lazy lazy-image-fadein-fast" data-blurhash="lo ...

How can I redirect after the back button is pressed?

I am currently working with a trio of apps and scripts. The first app allows the user to choose a value, which is then passed on to the second script. This script fetches data from a database and generates XML, which is subsequently posted to an Eclipse/J ...

I am currently facing an issue related to the length property. It is showing an ERROR TypeError: Cannot read property 'length' of undefined

Is it recommended to set the length to be inherited from Angular right? If so, why am I getting this error: "MyPostsComponent.html: 7 ERROR TypeError: Cannot read the 'length' of undefined property" when fileList.length is greater than 0? onFile ...

Incorporate CSS styling from a separate .css file into a material component

Just starting out with material UI. I have a css file that looks like this: .bgItem { font-size: 14px; } My component setup is as follows: <MenuItem key={status.Id} value={status.Value} classes={css.bgItem}> {status.Description} </Men ...

What is the process for combining three 2D arrays and showcasing the outcome as an image?

I am currently working with three 2D arrays that contain red, green, and blue pixel values of an image. The original image is blurred and then divided into these RGB arrays so that I can apply a function to each array in order to deblur the images. After t ...

Issue with toggleClass not functioning properly after receiving data from an AJAX call

On my website, I have a link that triggers an AJAX request. However, when the response comes back and I try to use the toggleClass function in the following .js code snippet, it doesn't work as expected: $(document).ready(function(){ $("td").click( ...

Error encountered in a Node.js Express application: 'Error in Jade template (version 1.0+): The usage of duplicate key "id" is not permitted.'

Seeking guidance on the following issue: Within my Express app, I am providing numerous parameters to a Jade template, resulting in an error message that states: Duplicate key "id" is not allowed. (After reviewing, I have confirmed that there is no para ...

Trouble with Bootstrap modal implementation when using ajax and looping through data

I am having an issue with using the BS modal to display a form containing a select box and updating records in the database via an ajax call. The trigger button to open the modal consists of <i></i> tags with the same class name, itagbtn, and d ...

Ways to extract a specific value from a geojson object using the key name

After making a call to the back-end, I retrieved the below geojson data in the 'data' object. However, when trying to access the values of the 'type' and 'features' keys within the geojson, I encountered difficulties. data["g ...

Trigger .gif on hover using ng-repeat in AngularJS

Many solutions to this problem involve using jQuery, such as the following examples: Stop a gif animation onload, on mouseover start the activation and Animating a gif on hover. However, I'm interested in achieving the same functionality using Angular ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...