javascript - Turn Observable Array into nested JSON -


i'm having problem getting array of information stored json.

i made fiddle illustrate problem. enter set of tags , take @ console see output.

more explanation:

so have input takes in comma-separated list of tags, format.

function createtagarray() {    // given input value of 'tag1, tag2, tag3'    // returns array = ['tag1', 'tag2', 'tag3'] }  

i thought needed next following: loop on array , create 'tag' object each item includes id tag , id of contact tag associated with.

each object pushed tags, observable array.

function single_tag(id, contactid, taglabel) {     var self = this;      self.id = id;     self.contactid = contactid;     self.taglabel = taglabel; }  function createtags() {   var array = createtagarray();    (var = 0; < array.length; i++) {     self.tags().push(new single_tag(uuid.generate(), self.contactid, array[i]));   } } 

then, converted json

self.contactinformation = function() {   return ko.tojs({     "id": self.contactid,     "firstname": self.firstname(),     "lastname": self.lastname(),     ... other fields ...     "tags": self.tags(),   }) } 

but, when inspect console output of calling function, tags collection of arrays, not nice json object.

messed tags json

how formatted correctly?

i tried this suggestion, , tag json structured correctly, stored escaped quotes, seems wrong.

thanks help!

i recommend knockout.mapping plugin ko, allow map complicated json structure view model, without declarations.

from documentation

let’s have javascript object looks this:

var data = {     name: 'scot',     children: [         { id : 1, name : 'alicw' }     ] } 

you can map view model without problems:

var viewmodel = ko.mapping.fromjs(data); 

now, let’s data updated without typos:

var data = {     name: 'scott',     children: [         { id : 1, name : 'alice' }     ] } 

two things have happened here: name changed scot scott , children[0].name changed alicw typo-free alice. can update viewmodel based on new data:

ko.mapping.fromjs(data, viewmodel); 

and name have changed expected. however, in children array, child (alicw) have been removed , new 1 (alice) added. not have expected. instead, have expected name property of child updated alicw alice, not entire child replaced!

...

to solve this, can specify key mapping plugin should use determine if object new or old. set this:

var mapping = {     'children': {         key: function(data) {             return ko.utils.unwrapobservable(data.id);         }     } } var viewmodel = ko.mapping.fromjs(data, mapping); 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -