Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all object keys that start with an underscore( _ )

I need to make an array of all the keys (not values) in the following object where the key starts with an _ underscore...

In the following snippet i am trying to get getSubscriptions() to return ["_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>
like image 245
Omar Avatar asked May 16 '19 04:05

Omar


People also ask

What is Obj key?

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

How do you get the keys of an array of objects?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How can you tell which key an object is in?

You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .


1 Answers

You can use Object.keys and Array.filter

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

let result = Object.keys(myObj).filter(v => v.startsWith("_"));
console.log(result);
like image 114
Nikhil Aggarwal Avatar answered Oct 07 '22 19:10

Nikhil Aggarwal