标准化Javascript对象属性的Clean方法 [英] Clean Method to Normalize Javascript Object Properties
问题描述
我有一个代表用户的javascript对象数组,如下所示:
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.
对于jQuery来说,$.extend()
选项是一个不错的选择,但是只有在您提前知道所有属性的情况下,该选项才有效.
For jQuery specific, the $.extend()
option is a good one, but will only work if you know ALL the properties ahead of time.
一些人提到这可能应该是服务器端的任务,尽管我通常对此表示同意,但是有两个原因导致我不在服务器端处理此问题: 1)如果说1000个对象中的900个仅包含9个可能属性中的1个,它将是一个较小的JSON对象. 2)需要添加空"属性,以满足将来可能会替换为某种缺少某些属性的东西的JS实用程序.
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.
推荐答案
由于您使用的是jQuery,因此您可以滥用 $.extend
Since you are using jQuery you can abuse $.extend
function Person(options){
return $.extend({
userName:"",
city: "",
state:"",
phone: ""
},options);
}
$.map([{}],Person)
更新
这里提供了一种动态默认属性的方法
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"}]
*/
这篇关于标准化Javascript对象属性的Clean方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!