Is there a way to iterate through an array and transform the child JSON data into an observable array

Although this may be a common issue with many solutions available on Stack Overflow, my search so far has been unsuccessful.

I have an array containing JSON strings. My goal is to loop through the array, convert the JSON into an observable array, and then access the properties "value", "name", and "price" in order to use them with Knockout.

Array with JSON :

0 : "{"value":"382","name":"Entrecoté med poteter og sånt..","price":295.0}"
1 : "{"value":"385","name":"Svinekoteletter","price":295.0}"
2 : "{"value":"386","name":"Pizza Margherita","price":255.0}"

Initial loop :

completeArray.forEach(function(c) {
            // How do I convert the JSON string to an observableArray ??
        });

Edited

If anyone else is looking for a solution, I've included the complete example below:

self.addFoodItemsToSubMenu = function (item) {
        var existingFIS = JSON.parse(ko.toJSON(item.foodItemList()));
        var newFIS = JSON.parse(ko.toJSON(self.selectedFoodItems()));
        var completeFIS = existingFIS.concat(newFIS);

        var resultArray = ko.observableArray(completeFIS.map(function (item) {
            var parsedResult = JSON.parse(item);
            var resultObject = {
                value: parsedResult.value,
                name: parsedResult.name,
                price: ko.observable(parsedResult.price)
            }
            return resultObject;
        }));

        item.foodItemList(resultArray());
        self.selectedFoodItems([]);
    }

Answer №1

Based on my understanding:

var finalResult = ko.observableArray(completeList.map(function(element) {
    return JSON.parse(element);
}));

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

Issues with JQuery Ajax file upload functionality in the client's browser causing upload problems

Seeking to integrate a profile picture upload feature with Ajax and JQuery I've been successful in uploading profile pictures to my database on various machines and mobile devices, including Chrome, Edge, Firefox, Safari, and Vivaldi. However, my cl ...

The MIME type 'text/plain' is not compatible with JavaScript in the AWS Load Balancer

My angular application is currently running on AWS ECS (EC2 Instance) behind a load balancer. I have noticed that when I access the application using the direct IP address of my EC2 instance, everything loads perfectly without any issues. However, when I t ...

Preventing sensitive user passwords from being exposed in JSON responses in Symfony 3

I've run into an issue while developing a Symfony app with an integrated REST API. When I make an API request to return a user entity as JSON, it includes the encrypted user password in the response. While the password is encrypted, I still want to av ...

Modify the color with JavaScript by manipulating the Document Object Model (DOM)

const elementBox = document.getElementsByClassName('box'); let colorAsStringVariable = '#FEC6F0'; let colorAsNumberVariable = #FEC6F0; Array.from(elementBox).forEach((element) =>{ element.style.backgroundColor = colorAs ...

Transform the array into an object containing corresponding key-value pairs

In my dataset, I have an array containing various values: [ { "factor": { "data": "f1", "val": [ "val1" ] } }, { "factor": { "data": "f2", "val": [ "val2" ] ...

What is the reason behind the widespread adoption of Node.js and NPM for the compilation of JavaScript libraries by

The widespread adoption of Node.js and NPM in the JavaScript community has left me perplexed. Why must we rely on such drastic measures? What issues are these tools aiming to resolve for us? [Update] I feel like my original question missed the mark. Fra ...

Displaying a loading image when opening an external link using window.open

When a pop-up is opened through a window.open() function for external sites, I am looking to display a loading image icon for the links. One approach I considered is to show the loading image in a 'div' and retrieve the content of the external s ...

Only a single array object is being deserialized from the Json data

For some reason, when I try to read from the Google Nearby Places API, my array only contains one object out of 20 after deserializing the json data. If anyone could shed light on this mystery, it would be greatly appreciated. This is the json data that I ...

What is the method for showcasing the input value on a webpage using Javascript?

Is there a way to dynamically display input values on a website? I've attempted to show the value, but it seems to stay static even when the input is altered. const rangeInput = document.querySelector(".range"); const valueInp = document.querySelec ...

Learn how to incorporate SAX parser into an Angular 2 project by utilizing TypeScript

Encountering challenges while trying to integrate the sax parser [parser.ts] into my project. import sax = require("sax"); export class MyParser { //my parser code } When attempting to utilize it [app.component.ts]: import {MyParser} from './pa ...

Guide on creating a message string by incorporating array values where available

I'm trying to show a warning to the user. I have an array that I split, and I always use the values in positions 0 and 1. Occasionally, there might be a value in position 2, but not always. I want to create a message string that displays the value of ...

Changing the order of element names depending on their location within the parent element using jQuery

<div class="content"> <div> <input type="text" name="newname[name]0"/> <div> <input type="text" name="newname[utility]0"/> <div> <textarea name="newname[text]0 ...

Configuring properties for a component by retrieving data from MongoDB using an API request

My current API call utilizes axios in the following format: Service.get('path/to/api', (status, data) => { this.setState({ ComponentData: data, loaded: true}); }); {this.state.loaded && <Component id={this.state.ComponentD ...

Can you explain the distinction between these two concepts in JavaScript?

I've come across an issue while assigning PHP values to JavaScript. var a = <?php echo 39; ?> JavaScript is throwing an error that says "Uncaught SyntaxError: Unexpected token ILLEGAL". However, when I assign PHP values in a slightly different ...

"My original CSS styles are being overridden by a template page's CSS code

I am encountering an issue where the fonts in my application are getting changed when I include a template page called template.html with CSS that includes body{ font-family:'Arial'}. The template page is being included using 'ng-include&apo ...

Functional React component using a stateless class within

I need some valuable suggestions for a specific scenario. I am interested in developing my own Datetimepicker react component. I have been exploring different codes to easily create a calendar and came across a Regular Class that generates the calendar. M ...

Dealing with objects where an array field can occasionally be assigned a null value

My JSON data structure looks like this: { "list": [ { "id": 1, "reference": null }, { "id": 2, "reference": [ { "name": name, &quo ...

Ways to "halt" an element once reaching a different element while scrolling

I'm attempting to recreate the interactive widget titled "Engage. Involve. Connect" found on this webpage: . The concept involves the widget remaining fixed at the bottom of the page until the user scrolls, at which point it dynamically positions itse ...

retrieve Excel document via POST request

I have a scenario where my API endpoint accepts JSON input and returns an Excel file directly instead of providing a link to download the file. How can I use JQuery AJAX to download this file? Here is the backend code snippet: public function postExcel() ...

Using React JSX to set a dynamic color when hovering over an element

Hello there! Thanks for taking the time to read my inquiry. I have been presented with a challenge involving a specific color chosen by the customer. This color plays a crucial role in the overall application context. I've successfully managed to cha ...