Isolating objects within a JSON array based on a single key

I am developing a system using Angular 6, and I need to create over 100 input fields. Since these inputs are used in multiple forms, I want to create a dynamic form. However, I'm trying to figure out the best way to connect the input configurations to the correct objects.

My initial approach was to define all the input fields and store their values based on the object they belong to, but I encountered some challenges.

 let inputs: FormBase<any>[] = [

      new InputTextForm({
        key: 'Id',
        label: 'Id',
        value: '',
        required: true,
        order: 1
      }),

      new InputTextForm({
        key: 'Name',
        label: 'Name',
        value: '',
        required: true,
        order: 2
      }),

      new InputTextForm({
        key: 'Description',
        label: 'Description',
        order: 3
      }),

      new InputTextForm({
        key: 'CanSplit',
        label: 'Can Split',
        order: 4
      }),

      new InputTextForm({
        key: 'PisRate',
        label: 'PIS Rate',
        order: 5
      }),
    ];


    return inputs.sort((a, b) => a.order - b.order);
  }

All objects are named InputTextForm, and I will need to filter them based on their keys. How can I filter and push an InputTextForm instance to another array based on its key?

Answer №1

Instead of relying on lodash, you can utilize the filter method available in array objects to achieve the same outcome. By opting for native JavaScript functions, you can avoid introducing unnecessary dependencies into your project.

let result = inputs.filter(i => i.key === 'TaxaPis') ; 
console.log(result);  // => [{key: 'TaxaPis', label: 'Taxa Pis',  order: 5}]

Answer №2

If you have not yet attempted to loop through the array and verify the key property each time, then give it a try.

An effective method for this task is using Lodash's _.forEach(). It allows you to iterate over an object like this:

_.forEach(someObject, function(value,key) { /* some function */})

or over an array like this:

_.forEach(someArray, function(value) { if (value.key == 'someVal') {/*code*/}})

Within the forEach loop, you can evaluate your values and if they meet certain criteria, add them to another array.

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

Modify a property of an object using the useState Hook, where the property name is dynamically retrieved from a variable

const [fee, setFee] = useState({newPatient:'',establishedPatient:''}) const field1='newPatient' const field2='establishedPatient' To modify the fee object properties, I am looking to dynamically assign ...

Tips for calculating the total count of a specific field within a JSON array with TypeScript

I have a JSON array. "user": { "value": [ { "customerNo": "1234" }, { "customerNo": "abcd" }, { "c ...

Generating distinctive content within the confines of the Selenium WebDriver

Is there a way to generate a unique username value for the signup page username textbox using selenium webdriver instead of hardcoding it? For example: driver.findElement(By.id("username")).sendKeys("Pinklin") ; When "Pinklin" is hardcoded, running the ...

Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet fr ...

Comparison Between Jquery and Emerging Javascript Frameworks and Libraries such as Angular, Ember, and React

As a ruby on rails developer, my recent foray into learning Angular and React has opened up new possibilities in the world of Javascript technologies. Despite reading comparison posts to gain insight into the reasons behind using different frameworks and l ...

I'm running into an InvalidSelectorError and I could use some assistance in properly defining

As I gaze upon a massive dom tree, my task using NodeJS/Selenium is to locate an element by the title attribute within an anchor tag and then click on the associated href. Despite being a newcomer to regex, I am encountering numerous errors already. Below ...

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...

Having issues with Bootstrap customization in an Angular 7 project

I am currently working on customizing a Bootstrap 4 theme within an Angular 7 project. After installing Bootstrap, I updated my angular .json file to include the following: "styles": [ "./node_modules/@angular/material/prebuilt-themes/de ...

"Troubleshooting: Resolving Compatibility Issues Between jQuery and XMLHttpRequest

I'm facing a situation with my website where the index.php page loads info.php through an AJAX call. The content from info.php is loaded using the following code: <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onready ...

Problem with React Native Camera: Camera display is not functioning correctly - React-Native-Vision-Camera Error

Hey there! I could really use some help with a tricky situation I'm facing in my React Native app, specifically regarding camera integration. Here's the scoop: The Issue: I'm working on a video recording application using React Native that ...

Text woven seamlessly with a series of different scenes

After contemplating the use of three.js for incorporating 3D visualization into my Sphinx extension for model visualization, I realized that the current tool I am using is outdated and not being maintained. The three.js library offers a variety of example ...

How does the Paginate Pipe effectively retrieve the array length in an Angular 2 application?

I find myself in an interesting situation where I have a piece of code that is functioning within my Angular 2 application - it's generating the correct value, but the method behind its success is unclear to me. Specifically, I am using ng2-paginatio ...

Master the art of directing your attention to a list element with ease using the tab function and jQuery

I've been tasked with creating a questionnaire for a client. They want the current active question to be displayed at 100% opacity, while the inactive questions should be at 20% opacity. Currently, when the page loads, all questions are dimmed to 20% ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: https://i.sstatic.net/lWL9Y.png Code Snippet: ...

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

Error: A DOMException was caught in the promise while trying to push the router

Currently, I am facing an issue while working with React. An Uncaught DOMException occurs when trying to push the router. This exception specifically happens when I attempt to push a new URL into the router using an event triggered from a button in a mod ...

Tips for real-time content updates on a server-side rendered express application

My social media app, built using Express, Pug, and JavaScript for server-side rendering, is fully functional. However, whenever I comment on a post, I need to manually reload the page to see the new comment displayed. I'm exploring ways to dynamicall ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

When the down key is pressed in a textarea, choose the list item

I have HTML similar to the following <div class="row"> <textarea id="txtArea" ng-model="input" ng-change="handleOnChange(input);getSearchField(input);" ng-click="search(input)" ng-focus="search(input);" ...

Developing a music playlist using javascript/angular (replicating array elements while linking nested objects)

I am currently working on creating a playlist for a music player within an Angular app that includes a shuffle feature. The actual shuffle function is not the issue, as I am utilizing the Fisher Yates Shuffle method and it is functioning correctly. When th ...