javascript - Knockout: Make observable object from array -
i have thought simple question solve... apparently not.
i have server returns list of objects (json) loads database. database, objects have id
attribute unique:
{ "stores": [ { "id": "1f0", "name": "foo", "address": "foo here street" }, { "id": "2b4", "name": "bar", "address": "bar here street" }, { "id": "3b4", "name": "baz", "address": "baz here street" } ] }
the idea pretty simple: want create observable (i'm guessing want observablearray) instead of array want object attributes id
attribute , value whole store
object:
{ "1f0": { "id": "1f0", "name": "foo", "address": "foo here street" }, "2b4": { "id": "2b4", "name": "bar", "address": "bar here street" }, "3b4": { "id": "3b4", "name": "baz", "address": "baz here street" } }
i don't need of fields (id
, name
or address
) observables (so don't think need mapping, right?). want know how create structure.
i've tried:
var self = this; self.stores = ko.observablearray(); [ . . . ] self.stores = ko.utils.arraymap( serverstores, function(store){ var retval = {}; retval[store['_id']] = store; return retval; });
but makes self.stores
of 3 object
s this:
[ { "1f0": { "id": "1f0", "name": "foo", "address": "foo here street" }, }, { "2b4": { "id": "2b4", "name": "bar", "address": "bar here street" }, }, { "3b4": { "id": "3b4", "name": "baz", "address": "baz here street" } } ]
which not want.
any appreciated. thank in advance.
you wouldn't want map
it, returns new array. 1 option loop through array , build object like:
var serversasobject = {}; ko.utils.arrayforeach(serverstores, function(store) { var id = store.id; if (id) { serversasobject[id] = store; } }); self.stores = ko.observable(serversasobject);
Comments
Post a Comment