I have an object like this , i want to map it to a class object Stock as given below .
Input Object
var inputJson = [{
"HS": " ",
"__EMPTY": 1,
"__EMPTY_1": " Pcs."
},
{
"HS": " RAS222PCAIBA",
"__EMPTY": 1,
"__EMPTY_1": " Pcs."
},
{
"HS": " SRK20CSS-S6/A1.6T",
"__EMPTY": -4,
"__EMPTY_1": " Pcs."
}]
Class
class Stocks {
model;
quantity;
type;
constructor(data) {
Object.assign(this, data);
}
}
i am trying to get the refined class object in an array like this
var completeStock = [] ;
$.each(inputJson, function( index, value ) {
completeStock.push(new Stocks(value));
});
But this is adding the object keys rather than mapping the first object key to model , second key to Quantity and ther third key to type. How can i achieve this .
3
Answers
You can modify your class constructor in the following way:
You can just extract out the values from object and assign them to the class properties like below
You need to clearly define the mappings in the constructor.
Your constructor will only work with the same property names of the
inputJson
.Modify your constructor like this, Now we have defined clear mappings in the constructor.
Now you will be able to map them correctly.