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>
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.
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.
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With