Having difficulty retrieving an item from a knockout observable array

When fetching data from a web API and pushing it into an observable array, I wanted to make the items in the array observable as well. Unfortunately, I found that I couldn't access the object if I made it observable.

function UpdateViewModel() {
  var vm = this;
  
  vm.ProfileInfo = ko.observableArray([]);
  
  vm.GetProfileData = function() {
    $.ajax({
      type: 'GET',
      success: function() {
        $.each(data.ProfileList, function (index, value) {
           vm.ProfileInfo.push(value);
           alert(vm.ProfileInfo()[index].Name) // Success
        }
      }
    });
  }
      
  vm.GetProfileData();
}
           
function UpdateViewModel() {
  var vm = this;
  
  vm.ProfileInfo = ko.observableArray([]);
  
  vm.GetProfileData = function() {
    $.ajax({
      type: 'GET',
      success: function() {
        $.each(data.ProfileList, function (index, value) {
           vm.ProfileInfo.push(ko.observable(value));
           alert(vm.ProfileInfo()[index].Name) // Fail. Object does not support property or method 'Name'
        }
      }
    });
  }
      
  vm.GetProfileData();
}

Answer №1

Are you simply pushing the object (turning it observable) into an observableArray? Doesn't quite sound right, does it? Perhaps consider making Name observable as well. However, you can still access the output using something like self.ProfileList()[index]().Name. Check it out here.

Here is a better approach:

ViewModel:

 function convert(data) {
    this.Name = ko.observable(data.Name)
    this.place = ko.observable(data.place)
    this.age = ko.observable(data.age)
}

function KnockoutViewModel() {
    var self = this;
    self.ProfileList = ko.observableArray([]);
    self.GetProfile = function () {
        var data = [{
            'Name': 'Super',
                'place': 'Ind',
                'age': 25
        }, {
            'Name': 'Cool',
                'place': 'Aus',
                'age': 15
        }]

        //Manual way with function defined 
        //self.ProfileList(ko.utils.arrayMap(data, function (value) {
        //  return new convert(value)
        //}))

        //Using Mapping Plugin
        ko.mapping.fromJS(data,{},self.ProfileList)
    }
    self.GetProfile();
}

ko.applyBindings(new KnockoutViewModel());

See a working sample here

Answer №2

Utilize the mapping functionality within the module:

This line of code will add value to the ProfileList array after wrapping its properties in knockout observables.

By doing this, knockout will automatically convert them into observables for you.

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

Alternative method to jQuery's "find" selector

$('.wrapper a').filter('a'); //returns all anchors I am trying to find a way to select all anchor elements using a specific selector. The issue is that the find method only looks at descendants, so I need an alternative solution. Any s ...

Hiding validation messages upon clicking in a textbox in ASP.NET MVC: a tutorial

When attempting to hide the validation message on click of the textbox, it remains visible. Can someone please provide assistance? <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @autoco ...

Manipulating the visibility of components by toggling on click events according to the existing state in ReactJS

Disclosure: I am still getting familiar with ReactJS I'm currently working on incorporating a dialog window for selecting a country/language on the initial page of my application. Here's the concept: There's a small flag button in the to ...

Dynamically Loading CSS files in a JQuery plugin using a Conditional Test

I'm trying to figure out the optimal way to dynamically load certain files based on specific conditions. Currently, I am loading three CSS files and two javascript files like this: <link href="core.min.css" rel="stylesheet" type="text/css"> & ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...

Handling Errors: Communicating with the Frontend

I'm facing a challenge with error handling in my authentication API calls. Whenever I trigger the 500 status from Express, my frontend (using Vue) only displays the message Request failed with status code 500 instead of something more informative like ...

Utilize async/await to send images using node mailer

How can I correctly access mailOptions in the triggerExample.ts file? mail.ts: export const sendNewMail = async (html: string, emails: string[]) => { let smtpTransport = nodemailer.createTransport({ service: "Gmail", auth: { u ...

Node.js unleashes the power of Ajax

I have seen some people ask this question before, but I am having trouble understanding the responses :/ I am working with node.js and really want to utilize Ajax in my project. Here is a snippet of my code: var $ = require('jquery'); var http ...

Ways to address the warning "promise rejections are deprecated"

I am struggling to understand promises and keep encountering an error about unhandled promise rejection, even though I have a catch block for handling rejections. Can anyone help me figure out what I am doing wrong? Below is the code I am working with: v ...

Utilizing Firebase Cloud Firestore: A guide to programmatically handling indexes

Transitioning from Firebase Realtime Database to Cloud Firestore has presented some challenges in implementing "complex" queries across collections. Despite this, I am determined to make it work. My current setup involves using Express JS and Firebase Adm ...

What is the best way to trigger a JavaScript function to execute as soon as the innerHtml has been modified via Ajax

Utilizing Ajax to dynamically update the content of a div upon clicking a link is my current project. I am seeking guidance on how to call a JavaScript function once the file has been retrieved from the server and the div's content has been replaced. ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

Node.js encountering an error caused by a lengthy SQL procedure execution, triggered by a POST request initiated from

Currently, my website utilizes Angular, NodeJs, and a SQL database. Most of the site's calls are made from the frontend to the backend and everything runs smoothly. However, I encountered an issue when running a stored procedure that had a longer proc ...

Adding various react elements to a list with the click of a button: A step-by-step guide

I am faced with a challenge where I have two different types of components that I want to display on the screen when a button is clicked. However, I don't want to simply show and hide the components. Instead, I want to be able to dynamically generate ...

Implement a delay for updating the style of a button by using the setTimeout function

Is it possible to create a button that, when clicked, changes color to green and then reverts back to its original style after 3 seconds? I am able to change the button color using an onClick event in my script. However, I encounter scope errors when tryi ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Ways to maximize the amount of content contained within a box

My current struggle involves meeting the requirements of my customers. I have a small box (230px x 200px) with an image that will display a list on hover. However, the customer now wants more items in the list than can fit in the box. Scrolling within the ...

Interactive hover effect in JavaScript displays a larger version of other thumbnails when hovering over a dynamically loaded thumbnail image, instead of its own full-size image

I recently began teaching myself PHP and Dreamweaver with the help of a video tutorial on building data-driven websites using Dreamweaver. My goal is to create a dynamic table with 6 columns and 20 rows. column1 | column2 | column3 | colu ...

The javascript function ceases to operate once the div is refreshed

$(function() { $(".reqdeb").click(function() { console.log("Functioning properly"); var req_id = $(this).attr("id"); var info = 'id=' + req_id; if (confirm("Confirm deletion of request?")) { $.ajax({ cache : false, ...