Retrieve values from a multi-level nested object by using square bracket notation for each level

I am in need of a config object to display nested data. Check out the demo code for reference

In the code, accessing "customer.something" is essential. There can be multiple levels of nesting, which the grid handles with field='customer.something'. How can I achieve the same using my template?

<e-column field='customer.something' headerText='Other' editType='dropdownedit' [edit]='editParams' width=120>

Below is the HTML file containing the template:

<ejs-grid #Grid [dataSource]='data' allowSorting='true'>
    <e-columns>
        <ng-template #colTemplate ngFor let-column [ngForOf]="colList">
            <e-column [field]='column.field' [headerText]='column.header' textAlign='Right' width=90>
                <ng-template #template let-data>
                    {{data[column.field] |  currency:'EUR'}} <-- looking to address this line
                </ng-template>
            </e-column>
        </ng-template>
    </e-columns>
</ejs-grid>

<!-- <ejs-grid #Grid [dataSource]='data' allowSorting='true'>
    <e-columns>
        <e-column field='price' isPrimaryKey='true' headerText='Price' textAlign='Right' width=90></e-column>
        <e-column field='customer.something' headerText='Other' editType='dropdownedit' [edit]='editParams' width=120>
        </e-column>
    </e-columns>
</ejs-grid> -->

Answer №1

One method to retrieve a specific field value using a string path is by utilizing a pipe. The following code demonstrates how this can be achieved:

@Pipe({name: 'fieldFromPath'})
export class FieldFromPathPipe implements PipeTransform {
  transform(data: Object, property: string): Object {
    property = property.replace(/\[(\w+)\]/g, '.$1');
    property = property.replace(/^\./, '');
    var a = property.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in data) {
            data = data[k];
        } else {
            return;
        }
    }
    return data;
  }
}

Then, in the template section, you can apply the pipe as shown below:

<ng-template #template let-data>
 {{data | fieldFromPath: column.field |  currency:'EUR'}}
</ng-template>

To view an example, you can visit this link: https://stackblitz.com/edit/angular-ej2syncfusion-angular-grid-jqm2kz

Note: The concept of extracting property values from a string path was inspired by a discussion on Stack Overflow. You can check it out here: Accessing nested JavaScript objects and arrays by string path

While this approach works, there may be alternative methods worth exploring for retrieving such values.

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

karma: Error: Unable to access the 'prototype' property of an undefined object

Whenever I attempt to inject my service, the following error occurs: (function () { describe('Test', function () { var $scope, $state, service,ctrl; beforeEach(function() { module('moduleApp'); ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

Techniques for manipulating multiple circles with JavaScript

After creating a series of circles with d3, I successfully implemented the functionality to drag individual circles and track their positions. var width= 800; var height=600; svg= d3.select("body").select(".div1").append("svg") ...

Optimal method for retrieving data from a JSON object using the object's ID with a map

Can you teach me how to locate a json object in JavaScript? Here is a sample Json: { "Employees" : [ { "userId":"rirani", "jobTitleName":"Developer", "preferredFullName":"Romin Irani", "employeeCode":"E1", "region":"CA", "phoneNumber":"408-1234567", " ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

What is the best way to obtain clear HTTP request data in a component?

My service retrieves JSON data from the backend: constructor(private http: Http) { }; getUsers(): Observable<any> { return this.http.get('http://127.0.0.1:8000/app_todo2/users_list'); }; In the component, this data is processed: ng ...

Hide button for the last input form to dynamically remove in jQuery

At first, I hide the remove button when there is only one form. However, if there are multiple forms and the user deletes all of them, I want the last form to remain visible and not be deleted. Can someone assist with this issue? Here is my code: <! ...

Attempting to add an element to an array results in an endless cycle

Here is a jsfiddle example showcasing the issue, but proceed with caution as it contains an infinite loop that can cause the browser tab to slow down and eventually freeze when the console is opened: https://jsfiddle.net/evx1j6yf/1/ Array Data: days: [ ...

Encountering a timeout error when connecting to MongoDB

Utilizing node.js v12.0.10, I have incorporated MongoDB database to establish a connection and update MongoDB collection with the following connection code: async.parallel({ RE5: function (cb) { MongoClient.connect(config.riskEngineDB ...

Error: 'Target is not found' during React Joyride setup

I am attempting to utilize React Joyride on a webpage that includes a modal. The modal is supposed to appear during step 3, with step 4 displaying inside the modal. However, I am encountering an issue where I receive a warning message stating "Target not m ...

An item was shown on the HTML page

Having some trouble displaying the graph generated by my R function on the opencpu server. Instead of the desired plot, all I see is [object Object] in the HTML page. Below is the snippet of code from my AngularJS controller: var req = ocpu.rpc("plotGraph ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

Determine the vertical dimension of an element through a JavaScript event listener

I've been working on creating an Apple-style image sequence scroller from a codepen demo. Here's the link to the original: https://codepen.io/jasprit-singh/pen/LYxzQjB My goal is to modify the JavaScript so that the scroll height is based on a p ...

Guide on sending information from a parent component to a child component in Angular using an event system

Is it possible to pass data from a parent component to a child component in Angular using a tab group? <mat-tab-group> <mat-tab label="Some text0"> <app-comp></app-comp1> </mat-tab> <mat-tab label="Some ...

Encountering the message "a critical error occurred: 'vips/vips8' file was not located" while using M2 (Apple Silicon) Macs

Encountered a pesky error that read: fatal error: 'vips/vips8' file not found while setting up a React project on my new M2 (Apple Silicon) device. After sifting through multiple reported issues on StackOverflow and github, I pinpointed the culp ...

Ensure your Vue components have type-checked props at compile time when using TypeScript

I have encountered an issue while using Vue.js with Typescript. The code I am working with is pretty straightforward, utilizing vue-class-component and vue-property-decorator. <script lang="ts"> import { Component, Prop, Vue } from 'vue-pro ...

Having trouble with VSCode/tsconfig path configurations, as the files are being fetched but still receiving a "Module not found" error in the editor

Since I began working on this project, I've been encountering a peculiar issue. When importing modules and files in my Angular components/classes using import, I face an error in VSCode when the paths use the base path symbol @. Strangely enough, desp ...

The function 'sendEmailVerification' is not a property of the type 'Promise<User>'

Hey there, I've been working on my ionic4 app and have encountered an issue with the sendEmailVerification function. The console is suggesting that I may have forgotten to use 'await'. Any ideas on how to resolve this? Thank you. import { In ...

Ways to showcase an alert or popup when clicking?

I am utilizing a date picker component from this site and have enabled the 'disablePast' prop to gray out past dates preventing selection. Is there a way to trigger an alert or popup when attempting to click on disabled days (past dates)? Any sug ...

Revising text for real-time editing

Most of us are familiar with the functionality on StackOverFlow that allows you to preview your text before posting a question. I'm interested in implementing a similar feature on my website and am looking for some guidance on how to get started. I ...