[英]select all object keys that start with an underscore( _ )
我需要在下面的对象中创建一个包含所有键(而不是值)的数组,其中键以_下划线开头...
在下面的代码片段中,我试图让getSubscriptions()
返回["_foo1", "_foo2"]
let myObj = { foo0: 'test', _foo1: 'test', _foo2: 'test', foo3: 'test', }; function getSubscriptions(obj, cb) { // should return ["_foo1", "_foo2"] let ret = ["foo1", "_foo2"]; return cb(ret); } getSubscriptions(myObj, (ret) => { if (match(ret, ["_foo1", "_foo2"]) ) { $('.nope').hide(); return $('.works').show(); } $('.nope').show(); $('.works').hide(); }); function match(arr1, arr2) { if(arr1.length !== arr2.length) { return false; } for(var i = arr1.length; i--;) { if(arr1[i] !== arr2[i]) { return false;} } return true; }
body { background: #333; color: #4ac388; padding: 2em; font-family: monospace; font-size: 19px; } .nope { color: #ce4242; } .container div{ padding: 1em; border: 3px dotted; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="works">It Works!</div> <div class="nope"> Doesn't Work...</div> </div>
您可以使用Object.keys和Array.filter
let myObj = { foo0: 'test', _foo1: 'test', _foo2: 'test', foo3: 'test', }; let result = Object.keys(myObj).filter(v => v.startsWith("_")); console.log(result);
将Object.keys
与filter
一起使用,并检查第一个字符是否为下划线_
:
let myObj = { foo0: 'test', _foo1: 'test', _foo2: 'test', foo3: 'test', }; const res = Object.keys(myObj).filter(([c]) => c == "_"); console.log(res);
替换你的getSubscriptions()
如下
function getSubscriptions(obj, cb) {
let ret = Object.keys(myObj).filter(ele => ele.startsWith('_'))
return cb(ret)
}
Object.keys(yourObject):返回yourobject的键。
Array.filter(function):根据数组返回过滤后的值
真实的情况
在过滤器中尝试.startsWith("_")
。
let myObj = { foo0: 'test', _foo1: 'test', _foo2: 'test', foo3: 'test', }; function getSubscriptions(obj, cb) { // should return ["_foo1", "_foo2"] let ret = Object.keys(myObj).filter(v => v.startsWith("_")); return cb(ret); } getSubscriptions(myObj, (ret) => { if (match(ret, ["_foo1", "_foo2"]) ) { $('.nope').hide(); $('.works').show(); } // $('.nope').show(); // you have misplaced these 2 lines //$('.works').hide(); }); function match(arr1, arr2) { if(arr1.length !== arr2.length) { return false; } for(var i = arr1.length; i--;) { if(arr1[i] !== arr2[i]) { return false;} } return true; }
body { background: #333; color: #4ac388; padding: 2em; font-family: monospace; font-size: 19px; } .nope { color: #ce4242; } .container div{ padding: 1em; border: 3px dotted; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="works">It Works!</div> <div class="nope"> Doesn't Work...</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.