Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  132] [ 7]  / answers: 1 / hits: 23913  / 12 Years ago, mon, may 21, 2012, 12:00:00

I'm currently working on a big JavaScript project and I'm struggling with mapping incomming JSON data (from the backend) to my own JavaScript objects.



I am using the Knockout JavaScript MVVM framework and although it includes a mapping plugin, it does not allow me to actually remap properties. I want to achieve this because the incomming JSON data is too fine grained, and I would like to 'flatten' my JS objects. An example follows.



Incomming data.



Object : {
Description: {
Id : 1,
Title : 'ProductX'
},
Price : {
Last : 12,
Currency : 3
}
}


And I would like to remap/flatten this to:



var mappedObject = {
id : 1,
title: 'ProductX',
price : 12,
currency : 3
}


Hence I would like to provide a mapping configuration, detailing what incomming properties should be mapped to what outgoing ones. Much like Dozer is being configured.



My question is: are there any libraries out there capable of what I'd like to achieve, or will this require me to build my own library?


More From » mapping

 Answers
15

Actually, the knockoutjs mapping plugin allows you to do just that:



In the ko.mapping.fromJS call you can provide a mapping object that will be used to map the containing properties...



var mapper = {
create: function(options){
return { name: ko.observable(options.data.name) };
}
};


This means that using this mapper with the mapping plugin, every object will be flattened to an object containing only it's name as an observable.



You use it like this:



var viewModel = ko.mapping.fromJS({id: 1, name: a, desc: b}, mapper);


In this case, viewModel will only have a property name.



You can read more about this feature in the official documentation here.


[#85456] Friday, May 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevenjeffreyr

Total Points: 286
Total Questions: 112
Total Answers: 95

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;