What JavaScript object to object mapping libraries exist?

javascript, mapping

Solution

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.

Problem

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?

Original source