Clean Method to Normalize Javascript Object Properties
javascript, jquery
Solution
Since you are using jQuery you can abuse $.extend
function Person(options){
return $.extend({
userName:"",
city: "",
state:"",
phone: ""
},options);
}
$.map([{}],Person)
update
Heres a way to have dynamic default properties
function mapDefaults(arr){
var defaultProperties = {}
for(var i =0; i < arr.length; i++){
$.each(arr[i],function(key){
defaultProperties[key] = "";
});
}
function Defaulter(obj){
return $.extend({},defaultProperties,obj);
}
return $.map(arr, Defaulter);
}
mapDefaults([{a:"valA"},{b:"valB"}]);
/* produces:
[{a:"valA",b:""},{a:"",b:"valB"}]
*/
Problem
I have an array of javascript objects that represent users, like so: ``` [ { userName: "Michael", city: "Boston" }, { userName: "Thomas", state: "California", phone: "555-5555" }, { userName: "Kathrine", phone: "444-4444" } ] ``` Some of the objects contain some properties but not others. What I need is a clean way to ensure ALL objects get the same properties. If they don't exist, I want them to have an empty string value, like so: ``` [ { userName: "Michael", city: "Boston", state: "", phone: "" }, { userName: "Thomas", city: "", state: "California", phone: "555-5555" }, { userName: "Kathrine", city: "", state: "", phone: "444-4444" } ] ``` Update I should have been a little more specific. I was looking for an option that would handle this situation dynamically, so I don't have to know the properties ahead of time. For jQuery specific, the `$.extend()` option is a good one, but will only work if you know ALL the properties ahead of time. A few have mentioned that this should probably be a server-side task, and while I normally agree with that, there are two reasons I'm not handling this at the server-side: 1) it will be a smaller JSON object if say 900 of 1000 objects only contain 1 of a possible 9 properties. 2) the "empty" properties need to be added to satisfy a JS utility that could be replaced in the future with something that doesn't care if some properties are missing.