Navigating over objects in Angular.Js

I'm looking to iterate through the JSON below to create a dynamic form in JavaScript. The challenge is that the keys and values are not the same. How can I accomplish this?

["register_form",
   {  
      "name":{  
         "fielde":"textfield",
         "description":""
      },
      "pass":{  
         "pass1":{  
            "field":"password"
         },
         "pass2":{  
            "field_type":"password"
         }
      },
      "mail":{  
         "field":"textfield",
         "description":""
      },
      "field_first_name":{  
         "field_type":"textfield",
         "description":""
      }
      
   }
]

none of these solutions are working for me:

//Get the size of object = no. of fileds to be created
var size = Object.keys(response[1]).length; 
console.log("Size..." + size);

console.log("Keys.." + Object.keys(response[1]));
var keys = [];
var model = [];
var label = [];
keys.push(Object.keys(response[1]));

for(var i=0;i<keys.length;i++) {
   angular.forEach(response[1].keys[i], function(key, value){
   console.log(key + "..." + value);            
});
          

Answer №2

Give this a shot

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

myApp.controller('myCtrl', function($scope, $sce){
$scope.user = {};
  $scope.registrationForm = {"username":{  
                         "field_type":"text",
                         "description":""
                      },
                      "password1":{ 
                            "field_type":"password"
                       },
                       "password2":{ 
                            "field_type":"password"
                       },
                      "email":{  
                         "field_type":"text",
                         "description":""
                      },
                      "first_name":{  
                         "field_type":"text",
                         "description":""
                      } };
  $scope.formData = { name : "" };
  $scope.html = "";
  angular.forEach($scope.registrationForm, function(value, key){
    $scope.html = $scope.html + "<input type="+ value.field_type +" placeholder="+key+" >";
   });
  $scope.trustedHtml = $sce.trustAsHtml($scope.html);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <form>
    <div ng-bind-html="trustedHtml">
    </div>
  </form>  
</div>

Answer №3

Updated

Here is the solution that should meet your requirements. Feel free to customize the output as needed.

var data = {  
      "name":{  
         "fielde":"textfield",
         "description":""
      },
      "pass":{  
         "pass1":{  
            "field":"password"
         },
         "pass2":{  
            "field_type":"password"
         }
      },
      "mail":{  
         "field":"textfield",
         "description":""
      },
      "field_first_name":{  
         "field_type":"textfield",
         "description":""
      }
   };
function toArray(obj) {
    var result = [];var passName;var tempArray = [];
    for (var prop in obj) {
        var value = obj[prop];
        if (typeof value === 'object') {
                $('#myForm').append("<br/><b>[[" + prop +"]]</b><br/>");

            if ($.isNumeric(prop)) {
                passName = name + "[" + prop + "]";
            } else {
                passName = name + "['" + prop + "']";
            }
            tempArray = toArray(value, passName);
            $.each(tempArray, function (key, value) {
                result.push(value);
            });
        } else {
        $('#myForm').append("<label>" + prop +"</label> : <span>" + obj[prop] + "</span><br/>");
            result.push(name + "['" + prop + "']");
        }
    }
    return result;
}

toArray(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myForm">

</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

Error encountered while trying to call callback functions

I encountered an error in my code, but I managed to resolve it independently. Could someone please provide an explanation of why the code wasn't working and delve into the mechanics behind the issue? Here is the code snippet: var listTables = functi ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

What are some creative ways to provide video responses to a list of questions?

My task is to create a popup that includes questions and video responses. The challenging aspect for me is how to ensure each question displays a different video in the same location. Additionally, when the user first opens the popup, the initial question ...

Dynamic content loading for Twitter Bootstrap Popover using Ajax

Below is my code for dynamic content loading in a popover using AJAX. The popover displays correctly after the initial load, but there is an issue with its behavior on the first "show" event – it appears and disappears immediately. $("a.mypopover"). ...

Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this? Here is ...

Encountering an issue with locating an argument in a JSON file

My JSON file seems to have an error, and I'm not sure where the issue lies within my data blocks. I attempted using jsonpathfinder for reading but encountered a syntax error. { "data": [ { "gender": "male" } ] }{ "data": [ { ...

Adjust the height of the Iframe to match the content within it

After conducting my research, I have not been able to find a solution. Although I am not an expert in jQuery, it seems that the code is not functioning properly. Within the iframe are links that expand when clicked to display content. However, the height o ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

JSON - The challenge of incorporating single quotes within double quotes

In my current scenario, I am using the following code to populate form fields. The code is designed to handle a JSON dataset that has been encoded with PHP's json_encode function. Everything works smoothly when dealing with either single or double qu ...

This JavaScript operates in solitude, unable to collaborate with other JavaScripts

I received this code from an outsourced programmer: <script type="text/javascript"> $(function(){ $('#notif-icons > li > a, #top-menu > li > a').click(function() { var clicked = $(this).next('.popup-notif&a ...

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

Press the button to dynamically update the CSS using PHP and AJAX

I have been facing challenges with Ajax, so I decided to switch to using plain JavaScript instead. My goal is to create a button on a banner that will allow me to toggle between two pre-existing CSS files to change the style of the page. I already have a f ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...

Retrieve any webpage using AJAX

Hey there! I'm a beginner in AJAX and have a question that may seem basic to some. I understand that you can set up a page to respond to an AJAX call, but is it possible to request any page with AJAX? In other words, can all the functionalities of a ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

How can I identify the blur or focusout event in a tinyMCE textarea?

I have been tackling with an existing project. Whenever I click on some editable text within the webpage, it transforms into a textarea and shows the tinyMCE toolbar. However, when I click outside of that textarea, the toolbar disappears. I am trying to fi ...

Running a Mongoimport command within a JavaScript/Node.js script

Is there a node.js/javascript library available that allows for the use of mongoimport within code? From what I understand, mongoimport is similar to an .exe file that needs to be executed before being able to utilize its text input environment. Is it fe ...

What should you do when you need to send a message from a website to an MQTT broker that lacks Websockets support?

Currently venturing into the realm of web development, I find myself tackling a project that involves sending messages from my website to Thingstream, an MQTT broker. My initial attempt using the MQTT Paho JavaScript library was thwarted by the fact that ...

Unable to execute JavaScript function by clicking

I've tried everything, but I can't seem to change the button text when selecting an item in the "Requirements" dropdown. You can view the issue on this site. Located at the bottom of the page is the "Requirements" dropdown. Each item has an oncl ...