Retrieve only the top-level items

I currently have an object selected using a selection box that is displayed on the page when the user makes a choice.

However, at the moment, it prints not only the parent object but also all the nested objects within it.

An example of my array

$scope.productsandformats = [
     {
                "Pname": "parent",
                "format": [
                    {"Fname": "child", "id": "4"},
                    {"Fname": "second child", "id": "5"}
                ]
            }
];

My Angular and HTML selection box

<select ng-model="formData.ProductType"
        ng-options="product.Pname for product in productsandformats">
     <option value="">- Please Choose -</option>
</select>

<pre class="col-sm-12 ng-binding">
   {{ formData }}
</pre>

So currently, when I select parent, I get:

{"ProductType":{"Pname":"parent","format":[{"Fname":"child","id":"4"},{"Fname":"second child","id":"5"}]}}

What I expect to see

{"ProductType":{"Pname":"parent"}}

What I need

I only want to display the Pname, such as parent, parent2, parent3, without including the children objects.

How can I modify this to show only the top-level object?

@George's answer almost works

The challenge is that the second dropdown should be populated with the child objects of the selected parent, resulting in the final string reading as follows if 'parent' is selected from the first option and 'second child' from the second option.

ProductType: Pname: parent, formatType: Fname: child

Angular code for both boxes, with the second one populated by children of the selected parent

 <select ng-model="formData.ProductType"
            ng-options="product.Pname for product in productsandformats">
        <option value="">- Please Choose -</option>
    </select>

    <select ng-model="formData.formatType"
            ng-options="format.Fname for format in formData.ProductType.format"
            ng-if="formData.ProductType">
        <option value="">- Please Choose -</option>
    </select>

Answer №1

If you take a look at the information provided on ngOptions, you will find that using select as allows you to specify which object is set on the ngModel.

To handle the second select, it is recommended to have an ng-change on the first select in order to store that object in another variable within the scope for use in the second select.

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.productsandformats = [{
    "Pname": "parent",
    "format": [{
      "Fname": "child",
      "id": "4"
    }, {
      "Fname": "second child",
      "id": "5"
    }]
  }];

  $scope.formats = [];

  $scope.productTypeChange = function() {
    $scope.formats = $scope.productsandformats.find(ps => ps.Pname == $scope.formData.ProductType.Pname);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <select ng-model="formData.ProductType.Pname" ng-change="productTypeChange()" ng-options="product.Pname as product.Pname for product in productsandformats">
    <option value="">- Please Choose -</option>
  </select>
    <select ng-model="formData.formatType" ng-options="format.Fname for format in formats.format" ng-if="formData.ProductType.Pname">
    <option value="">- Please Choose -</option>
  </select>
    <pre class="col-sm-12 ng-binding">
   {{ formData }}
   </pre>
  </div>

</div>

Answer №2

If you want to retrieve the first level object, you can use the following code:

<div ng-repeat='p in formData.productType'>
{{p.pname}}
</div>

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

Generating a new POST header

I have encountered a challenge: I need to transfer an array to another page without using AJAX. My goal is to either redirect the user to the new page or open a popup displaying the new page, all while ensuring the array data is sent via a POST request. C ...

Unable to reach controller action with Ajax request

I've been encountering issues trying to make a Get request to hit the specified URL. Initially, I attempted inputting the URL parameter manually in a separate JS file, then transitioning all my JS to cshtml to test out Razor. However, I am still facin ...

Can you find an `x` value that does not result in 1 when raised to the power of 0 using Math.pow()?

I recently came across a question that discussed the scenario where Math.pow(0, 0) === 1 evaluates to true. The documentation outlines the rules for x^y: If y is NaN, the result is NaN. If y is +0, the result is 1, even if x is NaN. If y is − ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

Guide on retrieving a value from a function that invokes $.getJSON

function searchAndRetrieve(searchTerm) { var defaultResult = 1010; var resultValue = defaultResult; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { ...

After applying styling, the modal close button refuses to be clicked

I'm currently facing an issue where I am trying to enhance a modal window with a close button, but encounter problems once styling is applied. The unique aspect of this problem arises from the fact that the close button is not directly in the page HTM ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

Tips on creating adaptable images for mobile viewing

My coding conundrum involves the use of two columns - one for an image and the other for a description of that image. However, when viewing my site on mobile devices, the image is cut off at only half its height. Adjusting both columns to col-sm-6 results ...

Setting a checkbox to true within the MUI Data Grid using my input onChange event - how can I achieve this?

I am looking to highlight the selected row in my usage input onChange event. https://i.stack.imgur.com/rp9rW.png Details of Columns: const columns = [ { field: 'part_code', headerName: 'Part Code', width: 200 }, { ...

Sending a string parameter from an AJAX function to a Spring controller

I'm currently developing a standalone application and facing an issue with passing a string, which is generated from the change event, to the spring controller using the provided code snippet. Here is the HTML CODE snippet: <!DOCTYPE HTML> < ...

What is the process for bringing an array from a .js file into an HTML document?

Exploring the world of JS and HTML, I recently came across an assignment that involved working with a file named stocks.js, which houses an array of stock information: 'use strict'; const stocks = [ { company: 'Splunk', symbol: &ap ...

Display popup depending on the post's identification number

Currently, I'm in the process of integrating Sanity into my blog. Using the json object returned from a query with useState, I managed to display my posts successfully. However, I am now faced with the challenge of populating a React-Modal with the ap ...

Leverage ESlint for optimal code quality in your expressjs

Is there a way to use ESlint with Express while maintaining the no-unused-vars rule? After enabling ESlint, I am encountering the following issue: https://i.stack.imgur.com/7841z.png I am interested in disabling the no-unused-vars rule exclusively for e ...

Executing NodeJS Functions in a Particular Order

Just starting to learn Node and working on building an app. Currently, in my route file, I am attempting to connect to MySQL and retrieve the major of the user, then use it for other operations. However, when I run the webpage, the console displays that t ...

Unable to retrieve response in Laravel ajax post, encountering issues either with errors or database insertion

My current issue involves making a POST ajax call to pass a form input value through a route to a controller that will execute an insert function. I have set up everything including the route, insert function, controller, and blade with the ajax call. Howe ...

Using withRouter() to redirect will display all components

I'm brand new to Reactjs and am currently diving into routing. In my journey, I stumbled upon the use of withRouter() for programmatic redirection. I had assumed the flow would follow: constructor->Willmount->render, but it seems the current or ...

Initiate a button click event from the parent element situated within an Iframe

I am facing a challenge in accessing a button within an iframe. The path to the button is as follows: div.iframe-container > iframe#builder-frame > html > body > div#header > ul.header-toolbar.hide > li > span.deploy-button-group.butt ...

React Native - Issue with Chart not updating correctly when new data is added

I'm struggling to create a dynamic chart using the Victory-Native library (click here for documentation). The goal is to modify the chart after pressing the "Get Data" button, but I've encountered a problem that has me stumped after hours of att ...

Send functions from the back-end Node to the front-end Angular

Introduction I am currently working on a project that involves verifying email addresses within an API in order to grant users access to a restricted section. To accomplish this, I have developed backend node code with three functions built using Node and ...

Retrieving a list from a C# function using JQuery ajax

I find myself in a bit of a dilemma while attempting to integrate C# and jQuery seamlessly. Within the same solution/project, I have a .cs file and a javascript document. The C# function I've written returns a list of strings, which I aim to append to ...