Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format:

{property: ["a","b"], value : "somevalue" , comparison : "somecomparison"}

I am looking for a way to transform it into a nested object like so:

{
  "properties": {
    "a": {
      "properties": {
         "b": {
            "somecomparision": "somevalue"
           }
         }
       }
     }   

What would be the most effective approach to implement this nested structure?

  {
      properties: {
        [property[0]: {
          [comparison]: value,
        },
      },
    }

Answer №1

To enhance the functionality of arrays, you can utilize the Array.flatMap() method to include a 'properties' key within the property array. After that, combine the comparison value with the array and leverage the Array.reduceRight() function to construct the final object. You can experiment with this in the TypeScript playgroundhere:

const fn = ({ property, value, comparision }) =>
  property
    .flatMap(p => ['properties', p])
    .concat(comparision)
    .reduceRight((acc, p) => ({ [p]: acc }), value)

const obj = {property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}

const result = fn(obj)

console.log(result)

Incorporating lodash libraries expands your capabilities further by introducing the _.set() function:

const fn = ({ property, value, comparision }) => 
  _.set(
    {}, 
    _.flatMap(property, p => ['properties', p]).concat(comparision),
    value
  )
  
const obj = {property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}

const result = fn(obj)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

"Exploring the methods to retrieve Firebase authentication error details and outputting the console log message along with

When I encounter an error in Firebase authentication, I want to display it in the console log. However, nothing is being logged and the catch block is not even getting executed. I am unsure about why this is happening and how to retrieve the error code and ...

Tips for effectively utilizing URLSearchParams in Angular 5 HttpClient's "get" function

When working with Angular 4.2, I used the Http service and made use of the get method by passing in a URLSearchParams object as the search parameter: this.http.get(url, {headers: this.setHeaders(), search: params}) Now I am looking to upgrade to Angular ...

Learn how to implement React Redux using React Hooks and correctly use the useDispatch function while ensuring type-checking

I'm curious about the implementation of Redux with Typescript in a React App. I have set up type-checking on Reducer and I'm using useTypedSelector from react-redux. The only issue I have is with loose type-checking inside the case statements of ...

The factory class is responsible for generating objects without specifying their type

I manage a factory that specializes in facilitating dependency injection. Here's an example of what it looks like: import SomeImportantObject from "./SomeImportantObject" import DataInterface from "./DataInterface" class NoodleFactory { this.depen ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

Testing in Vue revealed an unexpected absence of data

I am facing difficulties when it comes to creating tests. Currently, I have a view that is supposed to verify an email address using an authentication code. At the moment, the view exists but no connection is established with an email service or code gener ...

Why does Angular throw a length-related error, while I am able to retrieve the length using console log if needed?

It appears that Angular is not receiving the correct data type it expects, yet the lack of errors in the terminal is puzzling. However, the console output states: https://i.stack.imgur.com/1xPsg.jpg If the length property can be detected (highlighted in ...

Error with the type of CanvasGradient in the NPM package for converting text to image

I attempted to generate an image using a specific text by utilizing npm's text-to-image package, but encountered an error during typescript compilation. The errors I encountered upon running the typescript compilation command are related to files with ...

Retrieving data from a form input that utilizes reactive checkboxes

Hey there, I am currently working on implementing a Reactive Form and facing an issue with fetching values from checkboxes. It seems that only the value of the first checkbox selected is being recognized while the others are not. Below is the snippet of my ...

Sharing the label element as a prop in React component

I encountered the following code snippet: <div className="input-field"> <label htmlFor="timeObjective">Time Objective</label> <FrequencySet label='label'/> //HERE </div> My goal is to tra ...

Inquiring about Vue 3 with TypeScript and Enhancing Types for Compatibility with Plugins

I've been struggling to find a working example of how to implement type augmentation with Vue3 and TypeScript. I have searched for hours without success, trying to adapt the Vue2 documentation for Vue3. It appears that the Vue object in the vue-class ...

What might be causing my action function to be triggered during the rendering process?

While working on creating a basic card view in material UI, I encountered an issue where the functions for adding and deleting items seem to be triggered multiple times upon rendering. I am aware that a common reason for this could be using action={myFunc ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

Is ngOnDestroy executed within Angular services?

Is there a way to confirm if the ngOnDestroy method in my UserServiceService class is functioning properly? I want this service to continue running until the project starts and ends, with ngondestroy method executing once the application (website) is clo ...

Passing an observable from parameters to a pipe in RxJS: A guide

Can someone help me with writing a TypeScript function like the one below: function abc(arg1, arg2, arg3) { pipe(arg1, arg2, arg3...); // or someSubject.pipe(arg1, arg2, arg3..) } I keep getting errors when trying to build the code. How can I success ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

A guide on implementing TypeScript with React Native's platform-specific extensions

The issue at hand: In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as import useWifi from 'hooks/use-wifi.android';, everything works ...

Having trouble with customizing a selected ListItemButton in Material-UI - need some help with

After reviewing the documentation, I discovered a method to override the styling of the selected class by introducing a new class under .MuiSelected. The implementation looks something like this: const customStyles = makeStyles(() => ({ customizedSele ...

Am I utilizing Angular's signals correctly? And what is the purpose of still requiring ChangeDetectorRef.detectChanges()?

I have been experimenting with signals and I am questioning whether the current use case would be more beneficial without using Signals and instead just having a "normal" class member swiper?: Swiper: @Component({ selector: '[app-test]', stan ...