I have a knockout view model which consists of an observableArray of objects.
I am usig this json data to populate the array
This JSON structure is a simplified version of my real structure. In that, I want to give several attributes to one item, for example to control whether a form input is enabled or not: {"name":"George", "input_disabled":"true", "input_maxlength":"50}
etc
function listItem(id, name, address) {
var self = this;
self.id = ko.observable(id);
self.name = ko.observable(name);
self.address = ko.observable(address);
}
function vModel(data) {
var self = this;
self.listArray = ko.observableArray();
$.each(data, function(key, val) {
self.listArray.push(new listItem(val.id, val.name, val.address));
});
return {
listArray : self.listArray
}
}
var jsondata = [
{"id":"1"}, {"name":"George"}, {"age": "35"}, {"occupation": "Architect"}, {"address":"NY"},
{"id":"2"}, {"name":"Jerry"}, {"age": "35"}, {"occupation": "Comedian"}, {"address":"Brooklyn"},
{"id":"3"}, {"name":"Elaine"}, {"age": "35"}, {"occupation": "Publisher"}, {"address":"Manhattan"}
];
ko.applyBindings(new vModel(jsondata));
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table class="table table-striped">
<tbody data-bind="foreach: listArray()">
<tr>
<td>ID</td>
<td data-bind="text: id"></td>
</tr>
<tr>
<td>Name</td>
<td data-bind="text: name"></td>
</tr>
<tr>
<td>Address</td>
<td data-bind="text: address"></td>
</tr>
</tbody>
</table>
When I populate the array with the included JSON, the foreach loop prints out too many rows. As per the knockout documentation, the foreach loop duplicates the html elements for each item in the array.
But the question is, is there any way possible for me to get this JSON working with knockout? Or do I have to change the JSON similar to: var jsondata = [[{"id":"1"}, {"name":"George"}]]
etc
var jsondata = [{ "id": "1", "name": "George", "age": "35", "occupation": "Architect", "address": "NY" }, { "id": "2", "name": "Jerry", "age": "35", "occupation": "Comedian", "address": "Brooklyn" } ]
– Matin KajabadiObject.assign
. For example, in an ugly one-liner:jsondata.reduce((res, kvp, i) => (i % 5 ? Object.assign(res[res.length - 1], kvp) : res.push(kvp), res), [])
– user3297291