1

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..

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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];
  }
}

Comments

1

Here is the fiddle hope it helps you

 var q = [];
for(k in s)
{
 if(k.indexOf("d_") == 0){
 q.push(s[k]);
}

1 Comment

String.prototype.startsWith is part of the ES6 proposal. It's not available in many environments. In Chrome Canary your fiddle throws a TypeError.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.