标准功能,用于过滤对象和设置值

时间:2017-07-18 17:41:49

标签: javascript

我发现自己在控制器中使用不同的列表执行了15次以上。

class String {
    std::string m_s;
public:
    String(const std::string s) : m_s(s) { }
    String to_lower_copy() const {
        return {boost::to_lower_copy(m_s)};
    }
};

是否可以编写一个漂亮的小函数,所以我只需将其称为:

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 }

或类似的东西?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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));

希望它有所帮助,
最好的问候