一個非常簡單的解決辦法:你可以確保您的數據收集標準化,即所有屬性都存在於每個對象(null值,如果他們沒用過)。這樣的功能可以幫助:
function normalizeCollection (collection, properties) {
properties = properties || [];
return _.map(collection, function (obj) {
return _.assign({}, _.zipObject(properties, _.fill(Array(properties.length), null)), obj);
});
}
(注:_.zipObject
和_.fill
可在最新版本的lodash但不強調)
使用方法如下:
var coll = [
{ id: 1, name: "Eisenstein"},
{ id: 2 }
];
var c = normalizeCollection(coll, ["id", "name", "age"]);
// Output =>
// [
// { age: null, id: 1, name: "Eisenstein" },
// { age: null, id: 2, name: null }
// ]
當然,您不必永久轉換數據–只需調用模板渲染函數即可調用該函數:
var compiled = _.template(""); // Your template string here
// var output = compiled(data); // Instead of this
var output = compiled(normalizeCollection(data)); // Do this
如果您嘗試訪問model.foo.bar和酒吧不存在 – regretoverflow 2013-10-01 04:59:28
很好的知道,屬性訪問將不會引發錯誤仍然失敗。這正是我正在尋找的。我有一個對象,它可能包含一些數據。如果它不在那裏,我只是希望它被忽略。 – Andrei 2015-02-10 14:13:51