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

Preventing flickering when updating UI elements with AngularJS

A website I created showcases a variety of progress bars, each representing the progress of various backend tasks. For example: <div ng-repeat="job in jobs"> <div id="progressbar">...</div> </div> I am using a $resource for the ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

problem with displaying sidebar in Ember template

Using Ember, I have a login page where I don't want to display the header or sidebar navigation for my site until the user is authenticated. Once they are logged in, I want the header and sidebar to be visible. Currently, I am achieving this by checki ...

Challenges with window opening function while already in fullscreen view

Unsure of what might be causing the issue, but here's the problem... My code to open a new window is as follows: var opts = 'location=0,toolbar=0,menubar=0,scrollbars=0,resizable=0,height=450,width=300,right=350'; window.open('/' ...

Ways to access the new value of a cell in a Material UI Datagrid through the use of GridCellParams

When trying to access the newly modified value in a cell using the GridCellParams interface, I am faced with the issue that the 'value' property only provides me with the previous value of the cell. This asynchronous behavior is not ideal for my ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Can dates in the form of a String array be transmitted from the server to the client?

Struggling to send a String array from the server side to the client using Nodejs and Pug. Encounter errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal". Server runs o ...

The function inputLocalFont.addEventListener does not exist and cannot be executed

Help needed! I created a code to add images using PHP and JS, but I'm encountering an error in my JS that says: inputLocalFont.addEventListener is not a function Here's the code snippet: <div> <img src="<?php echo $img_path.& ...

Guide to swapping images on button click in HTML with dynamically changing image URLs retrieved from the server

I am a beginner in client-side scripting and new to Stack Overflow. I am looking for guidance on how to change an image within a div element upon clicking a button or anchor tag. Here is the code snippet I have written to achieve this: $scope.captchaCha ...

How about this: "Unveil the beauty of dynamically loaded

var request = new Request({ method: 'get', url: 'onlinestatusoutput.html.php', onComplete:function(response) { $('ajax-content').get('tween', {property: 'opacity', duration: 'long&apos ...

Ordering tables in jQuery with both ascending and descending options

Trying to sort a table in ascending and descending order using jQuery? Here's the JavaScript code for it. However, encountering an error: Cannot read property 'localeCompare' of undefined If you can provide guidance on how to fix this so ...

Animating the Bookmark Star with CSS: A Step-by-Step Guide

I found this interesting piece of code: let animation = document.getElementById('fave'); animation.addEventListener('click', function() { $(animation).toggleClass('animate'); }); .fave { width: 70px; height: 50px; p ...

Allow TypeScript function parameters to accept multiple elements from an enumeration

Enumerating my options. export enum Selection { CHOICE_ONE = 'one', CHOICE_TWO = 'two', CHOICE_THREE = 'three', CHOICE_FOUR = 'four', } I am looking to design a function that accepts an array, but re ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

I'm facing a challenge with retrieving the controller's scope in my Angular directive

Having trouble accessing the settings I receive from the server in my app. The directives are set up correctly and the $http is used to fetch a js file with the app settings. However, despite being able to log the scope in the console, I am unable to acces ...

The Angular 4 framework is a powerful tool for web development, offering

While attempting to iterate over an array, I noticed that the DOM is displaying [ object Object] instead of the desired information. Some sources suggested using Stringify to display the info, but it's not possible to iterate over a string. Any assist ...

Ways to add items to an array adjacent to items sharing a common property value

I have an array consisting of various objects const allRecords = [ { type: 'fruit', name: 'apple' }, { type: 'vegetable', name: 'celery' }, { type: 'meat', name: 'chi ...

ReactJs Unicode Integration with ID3 JS

I am working on a React Project that involves using an input type = "file" to upload music files. I am able to extract tags using ID3 Js, but the result is displayed in this format: https://i.stack.imgur.com/192co.png Is there a way to convert ...

What is the best way to retrieve web pages from the cache and automatically fill in form data when navigating to them from different pages on my website?

On my website, I have multiple pages featuring forms along with breadcrumbs navigation and main navigation. Interestingly enough, the main navigation and breadcrumbs share some similarities. However, my desire is that when users click on breadcrumb links, ...