1

I have a Knockout observable array with the internal structure shown below,

property: "Email"
value: "name@email.com"

I would need to convert it into a knockout Model object like this,

var obj;
obj.Email ="name@email.com";

Is there a simplistic way to achieve this in Knockout?

Thanks in advance

Anjan Saha
  • 57
  • 2
  • 3

2 Answers2

0

You can create a re-usable model to use in your view models. This is similar to using a class in C# to create objects that have common properties.

function objectModel(item) {
    var self = this;
    self.Name = ko.observable(item.name);
    self.Description = ko.observable(item.description);
}

Which can be invoked like -

var object = {
    name: 'John',
    description: 'a person'
}

var john = new objectModel(object);

Which could also be done by parameters instead of just objects -

function objectModel(name, description) {
    var self = this;
    self.Name = ko.observable(name);
    self.Description = ko.observable(description);
}

var john = new objectModel('John', 'a person');
PW Kad
  • 14,953
  • 7
  • 49
  • 82
0

Surely, the best way to map one object over to another is through knockout's utility function, arrayMap...for example, if you've got your array object...

var thisArray = [ 
    { property: 'Email', value: 'name@email.com'}, 
    { property: '', value: ''}... 
];

and you've got some other object type you're mapping to...

var newObject = function(email) { 
    var self = this;
    self.Email = email;
};

it's as simple as...

ko.utils.arrayMap(thisArray, function(arrayItem) { 
    if(arrayItem.property === 'Email')
        return new newObject(arrayItem.value);
});

Which returns a new array of newObject.

beauXjames
  • 8,222
  • 3
  • 49
  • 66
  • whatif the signature of newObject takes in multiple arguments and not one which in your case is Email, i though agree with PW Kad's solution but still i have to individually find which property is a Name or Email and then construct the object.... – Anjan Saha Dec 08 '13 at 06:18
  • well, depends. are these multiple arguments something you can put into your 'arrayItem'? If not, then you'd need to put them somewhere, right? You can always write a custom mapping routine with the ko.mapping plug in...there are more topics on SO for that as well. – beauXjames Dec 09 '13 at 21:00