Enhancing a child object using Knockout Mapping

Take a look at this JSON object:

{
    "BusinessModels":[
        { 
            "Id":1,
            "Name":"Business to Business",
            "Businesses":[],
            "ReportTypes":[
                {...},
                {...},
                {
                    "Id":6,
                    "Name":"Risk",
                    "BusinessModelId":1,
                    "Reports":[
                        {
                            "Id": 4,
                            "Name": "Test",
                            "Value": ko.observable() // NEED TO ADD THIS PROPERTY USING MAPPING
                        },
                        {...}
                    ]
                }
            ],
        }
    ]
}

I'm attempting to include the value using the code below, but it's not working as expected.

var mapping = {
    'BusinessModels': {
        create: function(options) {
            return new function() {
                var self = options.data;
                self.SelectedBusiness = ko.observable();
                self.Businesses.unshift({ Id: 0, Name: 'All Clients' });
                ko.mapping.fromJS(self, {}, this);
            };
        }
    },
    'Reports': {
        create: function (options) {
            return new function () {
                var self = options.data;
                self.Value = ko.observable();
                ko.mapping.fromJS(options.data, {}, this);
            };
         }
};

var model = ko.mapping.fromJSON(raw, mapping);
ko.applyBindings(model);

I need to assign a ko.observable object named Value to the child object "Reports". How can I achieve this using ko.mapping?

Answer №1

Wow, that didn't take long at all. I managed to solve the problem.

var mapping = {
    'BusinessModels': {
        create: function (options) {
            return new function () {
                var self = options.data;
                self.SelectedBusiness = ko.observable();
                self.Businesses.unshift({ Id: 0, Name: 'All Clients' });
                ko.mapping.fromJS(self, mapping, this);
            };
        }
    },
    'Reports': {
        create: function (options) {
            return new function () {
                var self = options.data;
                self.Value = ko.observable();
                ko.mapping.fromJS(self, mapping, this);
            };
        }
    }
};

Instead of

ko.mapping.fromJS(self, {}, this)
, I opted for
ko.mapping.fromJS(self, mapping, this)
. This decision was made because Reports is a nested object within BusinessModels.

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

I keep encountering a parser error when making an AJAX call to retrieve JSON data. It seems to be caused by

here is a snippet of code I am working on $.ajax({ type: 'GET', url: "<%=request.getContextPath()%>/manageUsers.do", cache: false, data:{ "resultType": "json", "submit": $.i18n.prop('esadmin.manage.users ...

AngularJS $routeProvider not working as expected

Today marks the beginning of my journey with AngularJS, and I'm facing a roadblock in the "routing" aspect. I've successfully created a controller and a view (refer below), but upon attempting to run it on my local server, an error pops up: Unca ...

Typescript - type assertion does not throw an error for an invalid value

When assigning a boolean for the key, I have to use a type assertion for the variable 'day' to avoid any errors. I don't simply do const day: Day = 2 because the value I receive is a string (dynamic value), and a type assertion is necessary ...

Ajax loaded scripts are unable to access global variables

Index.html <script> let bar = 1; </script> This html page is being loaded multiple times on the page using AJAX: article.html <script> if (bar === 1) { // perform a task } // Error: bar is not defined </script> Bar is a simple ...

JavaScript: determine if the default value has been changed

Can the default value of a field with id="someidset", set as value="abcdef", be detected if there is no prior information about this default value? I hope the question is clearly understood... ...

Unleashing the power of JavaScript: Sharing arrays and data structures effortlessly

Currently, I am utilizing HTML & JavaScript on the client side and NodeJs for the server side of my project. Incorporated in my form are multiple radio buttons. When the user clicks on the submit button, my intention is to post the results to the server. ...

Angular post request does not update the table

After displaying a table and a form on a page, I encountered an issue where the table does not update with new data when submitting the form. Even after refreshing the page, the new data is not reflected. As a newbie to Angular, I'm unsure of what exa ...

Incorporating jquery-ui Datepicker with dynamic text input functionality

In my table list, I have multiple input fields with the jQuery datepicker implemented. Each input field is assigned the class "datepicker" and a unique ID number. When clicked on, the datepicker pops up allowing for date selection to be inserted into the f ...

Integrate the elements from the <template> section into the designated <slot> area

I am trying to retrieve template content, insert it into a custom element with shadow DOM, and style the span elements inside the template using the ::slotted selector. However, it seems like this functionality is not working as I expected. <!doctype h ...

Navigate to all hyperlinks in browser without the use of jQuery - specifically for Firefox OS

I stumbled upon this interesting solution on a programming forum. I'm curious, how does this code work without relying on jquery? $('a[href^=http]').click(function(e){ e.preventDefault(); var activity = new MozActivity({ name: ...

Encountering a 405 Error Code while attempting to upload files with ng-file-upload

In an attempt to incorporate a file upload feature using ng-file-upload, I stumbled upon an example here that served as my reference. Despite everything appearing to function correctly, the issue arises when attempting to upload the file to my local webse ...

Transferring HTML variables to an Angular Component

I am currently trying to transfer the information inputted into a text-box field on my webpage to variables within the component file. These variables will then be utilized in the service file, which includes a function connected to the POST request I exec ...

Creating a new element with a specified ID attribute in JavaScript

I have written a piece of code that performs the following actions. It creates a paragraph element and then appends it to a div in the HTML. I would like to give this newly created paragraph element a unique identifier (ID) and set the name of the ID so th ...

Where should I place my elements to ensure proper positioning in the Code Generator?

Hey everyone, I've been working on developing a code generator similar to Sketch2Code and I've hit a roadblock with my JSON structure. I'm trying to create an HTML page using the myData example provided with a predefined HTML structure. Thin ...

Incorporating a GLTF Model in a Basic React Three Fiber Environment

I am attempting to incorporate a model with diffuse and bump textures into a basic scene using react 3 fiber. Despite my best efforts, I can't seem to figure out what mistake I might be making. You can view the sandbox here: https://codesandbox.io/s ...

What are some ways to conceal the API connection within a button?

I have a code that allows me to perform a certain API call with a link. Here is an example: <a class="btn btn-default" href="https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey='.$user.'&Password='.$pass.'&Domain=&ap ...

Displaying line breaks <br> on the browser when there are characters stored in the database

Within my mongo database, there is a document containing a field called reviewText: 'this is line 1\nthis is line 2',. This text was entered by a user in a textarea, hence the presence of \n to represent line breaks. I want to display t ...

Sending an array as JSON data to PHP using the $.ajax post method. The $_POST array is

After spending a considerable amount of time on this, I'm still struggling to figure out what I'm doing wrong. I'm having difficulty retrieving the data in the PHP file. I've made multiple calls to "copy" to populate the "result" arr ...

I am encountering an issue where the parameters I am sending through a POST request in Node.js

server.js: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); loggedIn = {}; app.use('/',express.static('www')); // static files app.use(bod ...

Encountered a problem while attempting to compare "unable to differentiate '[object Object]' with the array of objects inside another object."

I am encountering an issue in my console while attempting to extract data from an object nested within another object. I am uncertain about the correct method to map and return the necessary array of data, which is labeled as results in this scenario. Bel ...