选择所有以下划线(_)开头的对象键

Oma*_*mar 5 javascript arrays object ecmascript-6

我需要在以下对象中创建所有键(不是值)的数组,其中键以_下划线开头...

在以下代码段中,我尝试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; 
}
Run Code Online (Sandbox Code Playgroud)
body {
    background: #333;
    color: #4ac388;
    padding: 2em;
    font-family: monospace;
    font-size: 19px;
}
.nope {
  color: #ce4242;
}
.container div{
  padding: 1em;
  border: 3px dotted;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Nik*_*wal 9

您可以使用Object.keysArray.filter

let myObj = {
  foo0: 'test',
  _foo1: 'test',
  _foo2: 'test',
  foo3: 'test',
};

let result = Object.keys(myObj).filter(v => v.startsWith("_"));
console.log(result);
Run Code Online (Sandbox Code Playgroud)


Jac*_*ord 5

使用Object.keyswith filter,并检查第一个字符是否是下划线_

let myObj = {
  foo0: 'test',
  _foo1: 'test',
  _foo2: 'test',
  foo3: 'test',
};

const res = Object.keys(myObj).filter(([c]) => c == "_");
console.log(res);
Run Code Online (Sandbox Code Playgroud)