我发现自己在 Controller 中使用不同的列表执行此操作超过 15 次。
var selected = vm.countryList.filter(function(obj){return obj.id == vm.country})
if (selected.length) { selected[0].ticked = true }
var selected = vm.languageList.filter(function(obj){return obj.id == vm.language})
if (selected.length) { selected[0].ticked = true }
var selected = vm.propertyList.filter(function(obj){return obj.id == vm.property})
if (selected.length) { selected[0].ticked = true }
是否可以编写一个漂亮的小函数,所以我就这样调用它:
setTick(vm.property, vm.propertyList);
或者类似的东西?
最佳答案
您可以执行以下操作:
function setTick(propertyName) {
var selected = vm[propertyName + 'List'].filter(function(obj) {return obj.id == vm[propertyName]});
if (selected.length) { selected[0].ticked = true }
}
并像这样使用它:
setTick('language');
setTick('country');
在 ES6 中:
const setTick = (propertyName) => {
const selected = vm[`${propertyName}List`].filter(obj => obj.id == vm[propertyName]);
if (selected.hasOwnProperty('length'))
selected[0].ticked = true
}
// You can also use it like the following :
['language', 'country', 'property'].forEach(propName => setTick(propName));
希望有帮助,
最好的问候
关于javascript - 用于过滤对象和设置值的标准功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45173682/