Transmitting JSON data containing nested objects through AngularJS

Looking to modify the way I am sending a POST request with nested child objects. Here is the current format:

{
  "title": "sample string 2",
  "comment": "sample string 5",
  "child": {
    "name": "sample string 2"
  },
    "children": [
        {
            "name": "sample string"
        },
        {
            "name": "sample string"
        }
    ]
}

Currently, I am sending this:

{
  "title": "sample string 2",
  "comment": "sample string 5"
}

using this in the controller:

vm.product = new Product();
vm.product.title = "My title";
vm.product.comment = "my comment";

Here is the resource factory being used:

myApp.factory('Product', function ($resource) {
    return $resource('http://api.com/api/product/:id', { id: '@id' }, {
        update: {
            method: 'PUT'
        }
    });
});

Although the current setup works, I am looking to adjust the code to include child objects. I have tried:

vm.product.child.name = "my new child"

But unfortunately, it has not been successful. Any suggestions on how to implement this nested object structure?

Answer №1

To create and assign information to an object, follow these steps:

var child = { "name" : "my new child" };
vm.product.child = child;

It is not possible to directly assign a value to vm.product.child.name because the child object must be created first. Once vm.product.child is assigned, additional fields can be added to it. Another approach would be:

vm.product.child = {};
vm.product.child.name = "my new child";

If you need to create an array of children:

vm.product.children = [];
var child = {"name":"my child name"};
vm.product.children.push(child);

After setting vm.product.children as an array, you can add as many children as needed to it.

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

Retrieving the value from a dynamically-generated dropdown menu using jQuery

I created a tree list of data and I am attempting to update some information that is stored in a select element by sending a JSON post request to the edit action. Despite trying multiple approaches with jQuery, myself and my colleagues have been unsuccessf ...

When using CSS float:left and overflow:visible, the text may get cropped-off at

I'm currently experimenting with creating a color gradient in javascript using numerical values within some of the divs to indicate scale. However, I've run into an issue where as the values get larger, they are cut off due to the float:left prop ...

Implementing Node.js on several domains with the help of express.vhosts()

I'm facing a challenge with my nodejs setup. I am in the process of developing a node server that will support multiple instances of app.js running simultaneously on the same system using express.vhost(). However, I seem to have hit a roadblock. The ...

Creating an if statement that validates whether all variables have non-null values

I am still getting the hang of javascript and working on some coding projects from my textbooks. The current task involves creating an if statement to check if the values of the elements referenced by the names fname, lname, and zip are all not null. Here ...

The For loop with varying lengths that exclusively produces small numbers

I'm currently using a for loop that iterates a random number of times: for(var i = 0; i<Math.floor(Math.random()*100); i++){ var num = i } This method seems to be skewed towards producing lower numbers. After running it multiple times, the &apo ...

Choose a variety of table rows based on the values of the data attributes that are

Is there a more efficient way to select all rows with data attributes id 1,2.. without specifying each row individually? I need some guidance on the best approach for this. Can anyone help me out? <table id="eTable"> <tr data-empid="A123" data- ...

Having trouble correctly parsing XML data using JavaScript

My input field contains the following XML code: <?xml version="1.0" encoding="utf-8"?> <players timestamp="1536505850"> <player id="0518" name="Eagles, Philadelphia" position="Def" team="PHI" /> <player id="10271" name="Jones, Jul ...

Prevent event propagation in jQuery by using .stopPropagation() when hovering over a

When trying to implement event.stopPropagation() in a specific scenario, I encountered an issue with a blinking background image on my submenu. To address this, I added a pseudo-element (background:green) to the parent element by toggling a new class using ...

Loading an external template on the fly in AngularJS

As I work on creating a customizable table component in AngularJS, my goal is to have rows become editable when the user clicks an "Edit" button. The edited row should then display an input form bound to the model. To see my progress so far, you can check ...

Is there a way to set a personalized callback function when closing a modal with MicroModal?

I've been utilizing MicroModal for showcasing a modal window. Everything seems to be working smoothly, except for when I try to trigger an event upon closing the modal. It's unclear to me where exactly I should implement this callback function. ...

The success function within the Ajax code is malfunctioning

I am currently utilizing express, node.js, and MySQL. The issue I am facing is that the success function inside my Ajax code is not working as expected. Below is the snippet of the Ajax code in question: function GetData_1(){ var state = $("#dpState_1"). ...

Tips for easily consolidating JavaScript functions into a single file

I am currently dealing with a situation involving some basic IF / show/ hide scripts. I have successfully managed to get each individual script working on its own. However, when I try to combine them, they seem to conflict with each other and I am struggl ...

I am unable to reach my pages through their URL directly, I can only access them through links within Next.js

My next JS application runs smoothly during development, but encounters an issue when published online. I can only access the pages through links on the home page that direct to those specific pages. For instance, trying to navigate directly to www.examp ...

How can I utilize jQuery to save a simple text string in a mySQL database?

Seeking guidance on this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('im ...

Uncovering the origin of a problematic included file

When using Sencha Touch, it is common to encounter issues related to missing files. In most cases, simply including the file resolves the issue. However, there are instances where the problem lies in a faulty include, requiring you to locate where the file ...

Can anyone explain why the Splice function is removing the element at index 1 instead of index 0 as I specified?

selectedItems= [5,47] if(this.selectedItems.length > 1) { this.selectedItems= this.selectedItems.splice(0,1); } I am attempting to remove the element at index 0 which is 5 but unexpectedly it deletes the element at index ...

Retain the chosen values even after submitting the form

Consider the following form: <form method="get" action=""> <select name="name"> <option value="a">a</option> <option value="b">b</option> </select> <select name="location"> <opt ...

Using Vue to Bring in External JavaScript Files

If I have 2 JavaScript files located in the 'resources/assets/js' directory, named 'app.js' and 'ext_app.js', what could be the issue? Within 'ext_app.js' file, there is a function defined like this: function testF ...

retrieve the height value of a div element using AngularJS

I'm having trouble retrieving the updated height of a div using AngularJS. It seems to only provide the initial value and does not update as expected: vm.summaryHeight = $(".history-log-container").height(); console.log(vm.summaryHeight);//always dis ...

When using `res.send()`, an error of Type Error may be encountered stating that the callback is not a function. However, despite this error,

I am currently working on a function for my Node.js server, using Express as the framework and MongoDB as the database. This function involves calling two mongoose queries: (1) Retrieving filtered data from one collection (2) Aggregating data from anothe ...