猿问

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

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


在下面的代码片段中,我试图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>


慕勒3428872
浏览 541回答 4
4回答

慕森王

您可以使用Object.keys和Array.filterlet myObj = {&nbsp; foo0: 'test',&nbsp; _foo1: 'test',&nbsp; _foo2: 'test',&nbsp; foo3: 'test',};let result = Object.keys(myObj).filter(v => v.startsWith("_"));console.log(result);

慕哥9229398

使用Object.keys带filter,并检查第一个字符是一个下划线_:let myObj = {&nbsp; foo0: 'test',&nbsp; _foo1: 'test',&nbsp; _foo2: 'test',&nbsp; foo3: 'test',};const res = Object.keys(myObj).filter(([c]) => c == "_");console.log(res);

莫回无

替换您getSubscriptions()的如下&nbsp;function&nbsp;getSubscriptions(obj,&nbsp;cb)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;ret&nbsp;=&nbsp;Object.keys(myObj).filter(ele&nbsp;=>&nbsp;ele.startsWith('_')) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;cb(ret) &nbsp;&nbsp;&nbsp;&nbsp;}Object.keys(yourObject):返回yourobject的键。Array.filter(function):根据truthy条件从数组返回过滤值String.startsWith:如果传递的字符串以('_')开头,则返回true或false
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答