Javascript convert to array

265 Views Asked by At

I need to create an array of objects, with each object containing fields "LicenseRefNo", "FPPRNO" etc.

The website makes an ajax call to a C# controller which currently returns the following json:

"[{\"LicenseRefNo\":\"17/00031/HMO\",\"FPPRNO\":\"AGE146\"},{\"LicenseRefNo\":\"16/00031/HMO\",\"FPPRNO\":\"AGE146\"}]"

This seems to be almost correct but I need to set this as a gridOptions.data property of a KOGrid. It seems the javascript code is then running into a problem because the KOGrid needs to be an observable array, and to create one of these I need a javascript array.

How can I convert the string I have into an array please?

3

There are 3 best solutions below

1
ttncrch On BEST ANSWER

JSON.parse(string) should do the trick

1
subkonstrukt On

OberservableArray ships with knockout and you can create one with

edit: I created a fiddle with a working example since the posted seemed to be broken

var viewModel = function() {
    var yourLoadedArray =[{"LicenseRefNo":"17/00031/HMO","FPPRNO":"AGE146"},{"LicenseRefNo":"16/00031/HMO","FPPRNO":"AGE146"}]; 
   this.obsArr = ko.observableArray(yourLoadedArray);
    this.test = "test";
};

 
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: test"></span>
<div  data-bind="foreach: obsArr">
  <span  data-bind="text: LicenseRefNo"></span>
</div>

0
sjahan On

The JSON sample you posted is invalid, some quotes are weird and JSON.parse won't work directly. Here is a valid JSON content:

"[{\"LicenseRefNo\":\"17/00031/HMO\",\"FPPRNO\":\"AGE146\"},{\"LicenseRefNo\":\"16/00031/HMO\",\"FPPRNO\":\"AGE146\"}]"

Are you sure the content you posted is what you get? It's not even a valid string.