I have object with such fields:
{
d_name: { field_name: true },
d_date: { field_date: ISODate() },
status: 'success'
}
I need to get fields starting with d_ and then push them to one array..
I need to get fields...
Do you mean you need to get the keys? If so:
var d_keys = Object.keys(obj).filter(function (key) {
return !key.indexOf("d_");
});
If you actually want the values:
var d_values = Object.keys(obj).filter(function (key) {
return !key.indexOf("d_");
}).map(function (key) {
return obj[key];
});
Note that this uses various ES5 methods (Object.keys, Array.prototype.filter and Array.prototype.map), so depending on your environment you may need appropriate shims.
Here are working examples of both snippets.
You can iterate over the keys of the object, then compare the start of the key name:
var myObj = {
d_name: { field_name: true },
d_date: { field_date: ISODate() },
status: 'success'
};
var outArray = {};
for(var key in myObj) {
if(key.length >= 2 && key.substr(0,2) == "d_") {
outArray[key] = myObj[key];
}
}
Here is the fiddle hope it helps you
var q = [];
for(k in s)
{
if(k.indexOf("d_") == 0){
q.push(s[k]);
}
String.prototype.startsWith is part of the ES6 proposal. It's not available in many environments. In Chrome Canary your fiddle throws a TypeError.