0

This is probably a pretty known issue, and probably already solved in Stack Overflow, but I've searched without any luck.

I have this array which consists of a JSON-string. I'm trying to loop through the array, and convert the JSON to an observablearray so I can access the properties "value", "name", "price" so I can use it 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) {
            // convert the json string to an observableArray ??
        });

Edited

If someone else comes to find a solution to how to do this, I include 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([]);
    }

2 Answers 2

3

If I've understood you right:

var resultArray = ko.observableArray(completeArray.map(function(item) {
    return JSON.parse(item);
}));
Sign up to request clarification or add additional context in comments.

2 Comments

I see that this is the wanted result indeed!.. Will have to make the "price" property as observable though.. since it's going to be edited.. Know how i can do that ?
Okay.. your approach solved the riddle.. I have updated the question with the complete function, in case someone comes around to look for the same solution...
0

I would use map since it will loop through each item in the array, transform it, and spit it back out:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

2 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
I will check this as once :) Thanks for swift commenting!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.